简体   繁体   中英

Structs that refer to each other

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?

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.

The usual way of dealing with this is to make them pointers and then dynamically allocate them or even just assign the pointer from the address of a static instance of the other struct.

struct a {
  struct b *bb;
};

struct b {
  struct a *aa;
};

struct a a0;
struct b b0;

void f(void) {
  a0.bb = &b0;
  b0.aa = &a0;
}

I would suggest, however, that you look for a tree-structured organization. Perhaps both objects could point to a common third type.

This is nonsensical.

Imagine if you say that every X contains a Y and every Y contains an X , then inside each X is a Y which in turn contains an X , which in turn contains a Y , which in turn contains an X , ad infinitum .

Instead, you can have an X contain a reference to or (or pointer to ) a Y and vice-versa.

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