Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structs that refer to each other

Tags:

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?

like image 232
sjf Avatar asked Dec 09 '10 01:12

sjf


People also ask

Can a struct reference itself?

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.

Can you assign a struct to another struct in C?

Yes, you can assign one instance of a struct to another using a simple assignment statement.

Can structs have pointers?

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.


2 Answers

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.

like image 63
EboMike Avatar answered Jan 07 '23 09:01

EboMike


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.

like image 39
Muthuraman Avatar answered Jan 07 '23 09:01

Muthuraman