Warnings when creating a singly linked list with arrays

99封情书 提交于 2019-12-22 10:49:40

问题


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

Why do i get these warnings while compiling with gcc -Wall ? (even without -Wall, gcc produces the same warnings)

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]

回答1:


You are trying to use struct node inside the definition of node so therefore the compiler doesn't know you mean them to be the same thing. Try forward declaring the struct first:

struct node;
struct node
{
  int data;
  struct node *next;
};



回答2:


What @metalhead said was correct. Another probably better way to achieve the same result is

typedef struct _node
{
  int data;
  struct _node *next;
} node;

After this definition node (without underscore) can simply be used as a type name like e.g. int.

P.S. The underscore is just a standard convention, not a requirement. Any name could have been used in place of _node as long as you replace in both occurrences. However, in c this is a norm and sort of a coding convention that helps the devs to quickly understand _node refers to the node type actually.



来源:https://stackoverflow.com/questions/17085182/warnings-when-creating-a-singly-linked-list-with-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!