user138645
user138645

Reputation: 782

Warnings when creating a singly linked list with arrays

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

Upvotes: 3

Views: 342

Answers (2)

fkl
fkl

Reputation: 5535

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.

Upvotes: 6

metalhead
metalhead

Reputation: 567

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

Upvotes: 3

Related Questions