【问题标题】:Mutually referential structures in C [duplicate]C中的相互引用结构[重复]
【发布时间】:2015-06-29 14:13:34
【问题描述】:
struct A { 
    struct B b;
};
struct B {
    struct A a;
};
  • 请解释一下这些结构声明——它们有效吗?
  • 是否有此类声明的应用——如果有,您能举个例子吗?
  • 这些是自引用结构吗?

【问题讨论】:

  • 试着想象如果你能做到这一点会发生什么。它的大小是无限的。
  • @RetiredNinja 或零大小!
  • 为什么?假设您没有回答某种测验,您需要为这个问题添加一些上下文以使其有意义,而不是为使问题成为可接受的问题付出一些努力。

标签: c


【解决方案1】:

它是无效的,在像C 这样的程序语言中不需要。 (可能在对 ex 进行惰性求值的语言中很有用:Haskell)。

想象一下你的例子的用例

struct A { 
  struct B b;
};
struct B {
  struct A a;
};
Struct A a;
a.b.a.b.a.b.......[infinitely]

但是是的,有时您需要将AB 类型的结构相互引用,在这种情况下您可以使用指针。

struct child;
struct parent;

struct child { 
  ...
  struct parent *pParent;
};

struct parent {
  ...
  struct child *children[2];
};

现在可能的用例是:

struct child pikachu;
...
if(pikachu.pParent != NULL) {
  struct child *pPikachuSibling;
  pPikachuSibling = (pikachu.pParent.children[0] == &pikachu) ?
                           pikachu.pParent.children[1] :
                           pikachu.pParent.children[0];
  if(pPikachuSibling != NULL) {
    do_something_with(pPikachuSibling);
  }
}

C 中的字段不能有incomplete type[a],但允许字段是指向不完整类型的指针。

关于自引用结构体,使用指针,就可以实现这个需求。

assert( pikachu.pParent.children[0] == &pikachu) ||
        pikachu.pParent.children[1] == &pikachu) );

[a] 引用自ISO/IEC 9899:TC2 Committee Draft — May 6, 2005 WG14/N1124

109) 不完整类型只能在不需要该类型对象的大小时使用。它不是 需要,例如,当 typedef 名称被声明为结构或联合的说明符时,或 当声明一个指向或返回结构或联合的函数时。 (见不完整的类型 在 6.2.5 中。)在调用或定义此类函数之前,必须完成规范。

6.2.5 类型

22 未知大小的数组类型是不完整类型。这是 完成,对于该类型的标识符,通过指定大小 稍后声明(带有内部或外部链接)。一个结构或 未知内容的联合类型(如 6.7.2.3 中所述)是 不完整的类型。对于该类型的所有声明,它已完成, 通过声明相同的结构或联合标记及其定义内容 稍后在同一范围内。

【讨论】:

  • +1 使用口袋妖怪。
猜你喜欢
  • 2018-07-30
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 2021-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-28
相关资源
最近更新 更多