简体   繁体   English

相互引用的结构

[英]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: gcc说:

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... a将包含b ,其中包含a ,其中包含b等...

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 . 想象一下,如果你说每个X包含一个Y并且每个Y包含一个X ,那么每个X内部都是一个Y ,而Y又包含一个X ,而X又包含一个Y ,而Y又包含一个X无限的

Instead, you can have an X contain a reference to or (or pointer to ) a Y and vice-versa. 相反,您可以让X包含 Y引用或(或指向 ),反之亦然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM