7
struct node{  
    struct node next;  
    int id;  
}

gives "field next has incomplete type error ".

what is wrong with this struct ?

Prof. Falken
  • 24,226
  • 19
  • 100
  • 173
Qxtrml
  • 177
  • 2
  • 7

6 Answers6

16

When creating a self-referential data type, you need to use pointers to get around problems of circularity:

struct node;

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

...should work, but take care to allocate memory correctly when using it.

Why a pointer? Consider this: the point of a struct definition is so that the compiler can figure out how much memory to allocate and what parts to access when you say node.id. If your node struct contains another node struct, how much memory should the compiler allocate for a given node?

By using a pointer you get around this, because the compiler knows how much space to allocate for a pointer.

detly
  • 29,332
  • 18
  • 93
  • 152
5

If a struct could contain another instance of its own type, its size would be infinite.

This is why it can only contain a pointer to its it own type.

Furthermore, at that point in code, the size of the struct is unknown, so the compiler couldn't know how much space to reserve for it.

2
  1. You need to do a forward-declaration of node, since the compiler doesn't know node yet while it's processing its definition.
  2. You probably meant to store a pointer, not a node object itself.

Try this:

struct node;

struct node{  
    struct node *next;  
    int id;  
};
EboMike
  • 76,846
  • 14
  • 164
  • 167
  • The forward declaration is not needed as the struct's declaration acts as its own forward declaration. The issue is entirely that he tried to put a struct inside itself and should have used a pointer. – JeremyP Nov 04 '10 at 10:16
1

Some uses of incomplete types are ill-formed, such as when you try to declare an object of an incomplete type. However, you can declare a pointer to an incomplete type (for example). In this case that is just what is needed here:

struct node{  
    struct node *next;  
    int id;  
};
usta
  • 6,699
  • 3
  • 22
  • 39
0

The problem is, when the compiler reaches this line:

struct node{  
    struct node next;  /* << this line */

the compiler actually doesn't know what is struct node, because you're defining struct node.

In general, you cannot use a type which is not defined or incomplete.

Donotalo
  • 12,748
  • 25
  • 83
  • 121
  • 1
    Actually, the compiler *knows* that already. The real problem is that the `struct` will be of infinite size due to self-referentiality. The solution is to use a pointer (`struct node *next`). ;-) – Constantino Tsarouhas Dec 26 '12 at 22:09
0

In order to work, you should write:

typedef struct _node{
  struct _node* next;
  int           id;
}node; 
Xxxo
  • 11