I want to have two structs that can contain each other. Here is an example:
struct a { struct b bb; }; struct b { struct a aa; };
But this code doesn't compile. gcc says:
test.c:3: error: field ‘bb’ has incomplete type
Is there a way to achieve this?
Self Referential structures are those structures that have one or more pointers which point to the same type of structure, as their member. In other words, structures pointing to the same type of structures are self-referential in nature.
Yes, you can assign one instance of a struct to another using a simple assignment statement.
Declaring a structure pointer is similar to the declaration of a structure variable. To declare a structure pointer struct keyword is used followed by the structure name and pointer name with an asterisk * symbol. Members of a structure can be accessed from pointers using two ways that are.
How is that supposed to work? a
would contain b
, which would contain a
, which would contain b
, etc...
I suppose you want to use a pointer instead?
struct b; struct a { struct b *bb; }; struct b { struct a *aa; };
Even that though is bad coding style - circular dependencies should be avoided if possible.
struct a; struct b; struct a{ struct b *bb; }; struct b{ struct a *aa; };
Most of the header file declare the structure before defining its members. Structure definition will be defined in somewhere else.
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