Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next struct item,incomplete type [duplicate]

struct node{  
    struct node next;  
    int id;  
}

gives "field next has incomplete type error ".

what is wrong with this struct ?

like image 494
Qxtrml Avatar asked Nov 04 '10 07:11

Qxtrml


2 Answers

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.

like image 124
detly Avatar answered Oct 21 '22 03:10

detly


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.

like image 41
Martin Broadhurst Avatar answered Oct 21 '22 04:10

Martin Broadhurst