【发布时间】:2025-11-30 23:00:02
【问题描述】:
在暑假结束 C 编程之后,我又回到了最繁忙的课程中,并且正在努力赶上进度,尤其是在指针方面。
当前的分配让我们将程序从数组结构转换为简单的链表。为了刷新我的记忆,我尝试在一个独立的程序中实现它,但遇到了麻烦。
我的代码:
struct node{
int val;
struct node *next;
};
typedef struct node *item;
item newNode(void); //function prototype
void main(){
item *cur, *itemList;
int i;
itemList=NULL;
for (i=0; i<=10; i++){
cur= newNode();
cur->val=i;
cur->next= itemList;
}
}
item newNode(void) {
item box; /* the new object to return */
box = (item) malloc (sizeof (struct node));
if (box == NULL) {
printf("ERROR: emalloc failed for new Box\n");
exit(0);
}
/* initialize fields */
box->val=0;
return box;
}
第一条错误消息来自cur= newBox(),并指出正在对不兼容的指针类型进行分配。我不知道为什么,因为 cur 是一个指向节点的指针,而 box 是一个结构。不兼容的指针哪里来的?
【问题讨论】:
-
您调用了函数
newBox,但只声明了newNode,可能是调用中的拼写错误?请记住,C 具有“隐式 int”规则,其中假定未定义的函数具有原型int func() -
这是我帖子中的错字,而不是代码。我是这样编辑的
-
一般来说,我发现 typedef 被过度使用(就像这里它导致你的错误一样)。除非你能非常清楚地向你的猫解释你为什么使用它,否则不要使用它。
标签: c pointers linked-list