使用数组创建单链接列表时出现警告
#include typedef struct { int data; struct node *next; }node; void print(node *head) { node *tmp = head; while (tmp) { printf ("%d ", tmp->data); tmp = tmp->next; } } int main() { node arr[5] = { {1, &arr[1]}, {2, &arr[2]}, {3, &arr[3]}, {4, &arr[4]}, {5, NULL} }; print(arr); return 0; }
为什么在使用gcc -Wall编译时会收到这些警告? (即使没有-Wall,gcc会产生相同的警告)
list.c: In function 'print': list.c:15:7: warning: assignment from incompatible pointer type [enabled by default] list.c: In function 'main': list.c:22:18: warning: initialization from incompatible pointer type [enabled by default] list.c:22:18: warning: (near initialization for 'arr[0].next') [enabled by default] list.c:23:18: warning: initialization from incompatible pointer type [enabled by default] list.c:23:18: warning: (near initialization for 'arr[1].next') [enabled by default] list.c:24:18: warning: initialization from incompatible pointer type [enabled by default] list.c:24:18: warning: (near initialization for 'arr[2].next') [enabled by default] list.c:25:18: warning: initialization from incompatible pointer type [enabled by default] list.c:25:18: warning: (near initialization for 'arr[3].next') [enabled by default]
您正在尝试在struct node
定义中使用struct node
,因此编译器不知道您的意思是它们是同一个东西。 尝试首先声明结构:
struct node; struct node { int data; struct node *next; };
@metalhead说的是对的。 实现相同结果的另一种可能更好的方法是
typedef struct _node { int data; struct _node *next; } node;
在此定义之后, 节点 (没有下划线)可以简单地用作类型名称,例如int。
PS 下划线 只是一个标准惯例 ,而非要求。 只要您在两个匹配项中都替换,就可以使用任何名称代替_node。 但是,在c中,这是一种规范和一种编码约定,可帮助开发人员快速理解 _node 实际上是指节点类型 。