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(..., ¤t);
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.
struct Node
inside struct Node{}
it isn't yet determined. 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 *
.
struct Node *
, you know it's a pointer type. That needs a fixed amount of storage no matter what the type of pointer is.struct Node{}
. Hence it's a complete type.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With