c - 使用数组创建单链表时的警告

标签 c arrays linked-list typedef

#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;

在这个定义之后 node(没有下划线)可以简单地用作类型名称,例如诠释。

P.S. 下划线 只是一个标准约定,不是必需的。可以使用任何名称代替 _node,只要您在两次出现时都进行替换即可。 但是,在 c 中,这是一种规范和一种编码约定,可帮助开发人员快速理解 _node 实际上指的是节点类型

关于c - 使用数组创建单链表时的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17085182/

相关文章:

C 链表/-> 运算符

c - 数组中最大的数

c - 未映射的符号

python - 比较Python中的行元素

比较两个用户输入数组之间的元素?

c++ - C++中的通用链表

c++ - 在 Windows 中进行 C 或 C++ 编程时如何操作 GUID?

c++ - 系统日志自定义优先级

C 为结构体中的数组动态分配内存

c++ - 这段代码安全吗? (链表,C++)