相互引用的结构

发布于 2024-10-06 17:34:25 字数 234 浏览 2 评论 0原文

我想要两个可以相互包含的结构。这是一个例子:

struct a {
  struct b bb;
};

struct b {
  struct a aa;
};

但是这段代码无法编译。 gcc 说:

test.c:3: error: field ‘bb’ has incomplete type

有办法实现这一点吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

姜生凉生 2024-10-13 17:34:25

那应该如何运作? a 将包含 b,其中将包含 a,其中将包含 b 等等...

我想你想改用指针吗?

struct b;

struct a {
  struct b *bb;
};

struct b {
  struct a *aa;
};

即使这是不好的编码风格 - 如果可能的话应该避免循环依赖。

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.

云裳 2024-10-13 17:34:25
struct a;
struct b;

struct a{
   struct b *bb;
};

struct b{
   struct a *aa;
};

大多数头文件在定义其成员之前声明结构。结构定义将在其他地方定义。

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.

温柔戏命师 2024-10-13 17:34:25

处理这个问题的通常方法是使它们成为指针,然后动态分配它们,甚至只是从另一个结构的静态实例的地址分配指针。

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;
}

不过,我建议您寻找树形结构的组织。也许这两个对象都可以指向共同的第三种类型。

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.

陌上青苔 2024-10-13 17:34:25

这是无稽之谈。

想象一下,如果您说每个 X 都包含一个 Y 并且每个 Y 都包含一个 X,那么在每个 >X 是一个 Y,它又包含一个 X,后者又包含一个 Y,后者又包含一个 < code>X,无限

相反,您可以让 X 包含对 Y引用或(或指向Y,反之亦然 -反之亦然。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文