#include <stdio.h>
#include <stdlib.h>
typedef struct{
int data;
struct Node* next;
}Node;
Node* head;
void AddEntry(){
int x;
Node* temp;
temp = head;
while(temp != NULL){
temp = temp->next;
}
Node* temp1 = (Node*)malloc(sizeof(Node));
temp->next = temp1;
printf("What is the value for this entry?\n");
scanf("%d",&x);
temp1->data = x;
temp1->next = NULL;
}
void PrintList(){
Node* temp;
}
int main(void){
}
当我编译这段代码时,我得到了编译器错误:
pointertest.c: In function ‘AddEntry’:
pointertest.c:16:8: warning: assignment from incompatible pointer type [enabled by default]
temp = temp->next;
^
pointertest.c:19:13: warning: assignment from incompatible pointer type [enabled by default]
temp->next = temp1;
我不明白为什么会这样。我已经在我的教科书和其他地方看到了这一点。我以为是将指针temp分配给temp中保存的地址。
感谢您的帮助
答案 0 :(得分:3)
您的结构定义是假的。试试这个:
typedef struct tagNode {
int data;
struct tagNode *next;
} Node;
在您的代码中,没有struct Node
这样的内容,只有一个名为typedef
的“别名”(Node
)的未命名结构。
通过这种方式定义,您可以通过以下任一方式声明此类型的变量:
struct tagNode foo;
或者:
Node foo;
但是当我typedef
struct
这样的时候,我会避免使用标签来避免混淆。
评论中提到,为什么我选择使用struct tagNode
代替struct Node
可能会让人感到困惑。两者都同样有效,但我个人的偏好是使用不同的名称以避免以后混淆。如果我刚刚使用struct tagNode *foo
,我发现从Node *foo
可以直观地消除歧义struct Node
。
答案 1 :(得分:3)
您的代码中没有struct Node
。
这是匿名结构的typedef
typedef struct {
int data;
struct Node* next;
} Node;
在c中有效,但到目前为止还没有声明struct Node
,你需要
typedef struct Node {
int data;
struct Node* next;
} Node;
无论如何你要去typedef
,你也可以这样做
typedef struct Node Node;
struct Node
{
int data;
Node *next;
};