The next structural element, an incomplete type

struct node{ struct node next; int id; } 

gives the following field: error of incomplete type.

what is wrong with this structure?

+2
source share
6 answers

When creating a self-referencing data type, you need to use pointers to solve roundness problems:

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

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

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

Using a pointer, you get around this because the compiler knows how much space is allocated for the pointer.

+10
source

If the structure can contain another instance of its type, its size will be infinite.

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

In addition, at this point in the code, the size of the structure is unknown, so the compiler could not know how much space to reserve for it.

+5
source
  • You need to execute the forward declaration of the node, since the compiler does not know the node , but when processing its definition.
  • You probably wanted to keep the pointer, not the node object itself.

Try the following:

 struct node; struct node{ struct node *next; int id; }; 
+2
source

Some uses of incomplete types are poorly formed, for example, 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, this is what you need here:

 struct node{ struct node *next; int id; }; 
+1
source

The problem is when the compiler reaches this line:

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

the compiler really does not know what a struct node is because you are defining a struct node .

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

0
source

To work, you must write:

 typedef struct _node{ struct _node* next; int id; }node; 
0
source

Source: https://habr.com/ru/post/946841/


All Articles