Struct X in Struct X?

this is probably very simple, but how can I get structure x in structure x in C? For example:

typedef struct _Node { Node node; } Node; 

I did some research and tried using pointers, for example:

 typedef struct _Node { struct Node *node; } Node; 

Although this leaves the node variable as a pointer that I don't want, I just want it to be an instance of the node structure. Thanks for any help. :)

EDIT:

Essentially, I'm trying to do the following:

 Node current = createNode(...); while (true) { Node node = createNode(..., &current); addToList(node); current = somethingElse(); } 

As you can imagine, I want a regular node to go into the createNode () function:

 Node createNode(..., Node node) {} 
+6
source share
2 answers

It's impossible. Because it falls under the incomplete type. No struct Node inside struct Node inside struct Node ... etc. This makes your original structure incomplete. Therefore, the definition of an incomplete type.

The reason is that.

  • For the field to be inside the structure, it must be a known type.
  • But by the time we see the struct Node inside the struct Node{} , it is not defined yet.
  • It is determined only after scanning the entire definition of struct Node{} , but this is possible only after you recognize the type of struct Node inside, which leads to paradox .

But the case is different if you included struct Node * .

  • When you reach the struct Node * , you know that it is a pointer type. This requires a fixed amount of memory regardless of the type of pointer.
  • Thus, it successfully scans it and finishes the definition of struct Node{} . Therefore, it is a complete type.
+3
source
 typedef struct node { struct node node; } node_s; 

This will lead to "infinite recursion". In other words, its size would be infinite. The compiler cannot answer this question: how much memory should be allocated? Therefore, it issues a diagnostic message.

This is why you should use pointers to create self-referencing types.

 typedef struct node { struct node *node; } node_s; 

By the way, identifiers starting with an underscore, followed by an underscore or capital letter, are reserved for implementation.

+8
source

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


All Articles