简体   繁体   中英

Struct X in Struct X?

this is probably really simple, but how can I get a struct x to be in struct x in C? So for example:

typedef struct _Node {
    Node node;
} Node;

I've done some research and tried using pointers, like this:

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

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

EDIT:

Essentially what I'm trying to do is:

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

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

Node createNode(..., Node node) {}
typedef struct node {
    struct node node;
} node_s;

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

That's why you have to use pointers to create self-referential 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 to the implementation.

That isn't possible. Because that comes under incomplete type. No struct Node inside struct Node inside struct Node ...and so on.... That makes your original structure incomplete. Hence incomplete type definition.

The reason is that.

  1. In order a field to be inside a structure, it has to be a known type.
  2. But by the time we see struct Node inside struct Node{} it isn't yet determined.
  3. It's only determined after scanning all definition of struct Node{} but that's only possible after knowing the type of struct Node inside which leads to a paradox .

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

  1. When you reach struct Node * , you know it's a pointer type. That needs a fixed amount of storage no matter what the type of pointer is.
  2. So, it successfully scans it and finishes the definition of struct Node{} . Hence it's a complete type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM