开发者

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 t开发者_如何学编程o 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜