#include <stdio.h>
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]
@metalhead说的没错。另一种可能达到相同结果的更好方法是
typedef struct _node
{
int data;
struct _node *next;
} node;
在此定义之后节点(不带下划线)可以简单地用作类型名称,例如int。
注:下划线是只是一个标准约定,不是必需的。任何名称都可以用来代替_node,只要在两次出现时都进行替换。然而,在c语言中,这是一种规范和编码约定,可以帮助开发人员快速理解_node实际上指的是节点类型。 您试图在node
的定义内使用struct node
,因此编译器不知道您的意思是它们是同一件事。尝试先向前声明结构体:struct node;
struct node
{
int data;
struct node *next;
};