我正在启动堆栈代码,但这是一个问题
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct stackNode
{
int data;
struct stackNode *nextPtr;
};
typedef struct stackNode StackNode;
typedef StackNode *StackNodePtr;
void instructions()
{
printf("Please enter a choice\n");
printf("[1]Push a value on the stack\n");
printf("[2]Pop a value off the stack\n");
printf("[3]Display the whole stack\n");
printf("[4]Exit");
}
void push(StackNodePtr *topPtr, int info)
{
StackNodePtr newPtr;
newPtr=malloc (sizeof ( StackNode ));
if(newPtr !=NULL)
{
newPtr->data=info;
newPtr->nextPtr=*topPtr;
*topPtr = newPtr;
}
}
int main()
{
instructions();
system("pause");
}
我的代码出了什么问题?
这是问题
newPtr = malloc(sizeof (StackNode));
它表示从void*
到StackNode*
编译并查看它是否可行
我该如何解决这个问题?我该怎么编辑?
答案 0 :(得分:1)
更新:关于malloc的问题,只需转换为正确的类型:
newPtr = (StackNodePtr)malloc(sizeof (StackNode));
<小时/> 至于程序的其余部分 - 从说明()判断,您应该能够在键盘上输入不同的选项1,2,3或4.
你的问题就在这里开始,你需要实际检查“getch()”返回的键,如下所示:
char c = getch();
if (4 == c)
{
exit(0);
}
if (3 == c)
{
display_stack();
}
等
此外,由于你有一个退出选择(4),你应该包含循环中的所有内容:
while (1)
{
if-code应该在这里
}
您还需要实际创建display_stack()函数。
为了帮助您使用C ++编译器而不是C编译器(假设使用malloc进行转换),您需要告诉我们您正在使用的开发环境。
答案 1 :(得分:0)
由于你在main的末尾没有return语句,我假设你将代码编译为C ++,但问题是你的代码是C!
在C中,你不必强制转换malloc,但你必须使用C ++。
如果你制作C或C ++,请注意清楚说明。
如果您使用GNU编译器集合,请注意使用gcc而不是g ++来编译.c文件。
答案 2 :(得分:0)
从void *无效转换为StackNode *
这意味着您正在使用C ++编译器。在C ++中,如果没有强制转换,则不允许从void*
转换为另一种指针类型。在C中,允许转换,因此您不需要将调用的结果转换为C中的malloc
。有些人认为转换结果可能会掩盖一个更基本的问题,即假定未声明的函数返回{ {1}}。