【问题标题】:Limitations in "struct inside struct"“结构内部结构”的限制
【发布时间】:2016-09-22 19:38:20
【问题描述】:

有 2 个struct 定义AA。我知道struct A 可以包含 POINTERstruct A,但我不明白为什么 struct A 不能 包含 struct A(不是指针)

【问题讨论】:

  • 我会再回答这个问题 - 也许手头有字典
  • 不太明白你的问题,伙计
  • Struct inside struct的可能重复
  • 所以你想要Turtles all the way down
  • 不重复。 @Koni 询问如何在不使用指针的情况下创建递归结构。

标签: c struct


【解决方案1】:

因为当您将结构相互放入时,您就是在此时将该结构的 另一个副本 放入该结构中。例如:

struct A {
    int q;
    int w;
};
struct B {
    int x;
    struct A y;
    int z;
};

这将像这样在内存中布置:

int /*B.*/x;
int /*A.*/q;
int /*A.*/w;
int /*B.*/z;

但是如果你尝试在自身内部放置一个结构体:

struct A {
    int x;
    struct A y;
};

你有一个 A,它包含一个 int 和另一个 A,它包含一个 int 和另一个 A,现在你有无限数量的 int。

【讨论】:

    【解决方案2】:

    因为在这种情况下,它将占用无限存储空间,因为它必须递归地存储自己类型的数据成员。所以,这是不可能的。而指针的大小是固定的,因此不会造成任何问题。

    【讨论】:

      【解决方案3】:

      假设它可以包含自己类型的对象:

      struct A_
      {
         A_ a;
         int b;
      } A;
      

      sizeof(A) 是什么?答:sizeof(A)+sizeof(int):不可能。

      【讨论】:

        【解决方案4】:

        因为直到结束大括号} 才完成结构定义。要声明一个结构成员,编译器需要完整的定义,因为它使用该信息来计算空间、填充和对齐等内容。对于指向某个东西的指针,指针的大小就是指针的大小,编译器需要的所有内容os 类型的名称,而不是其完整定义。

        我们以一个简单的结构为例:

        struct A   // Here the compiler knows that there is a structure named A
                   // The compiler does not know its contents, nor its size
        {
            // Some members...
        
            struct A *pointer_to_a;  // All the compiler needs to know is the symbol A
                                     // The size and alignment is that of a pointer
                                     // and those are known by the compiler
        
            // Some more members...
        
            // struct A instance_of_A;  // This is not possible! At this point the
                                        // compiler doesn't have the full definition
                                        // of the structure, and can therefore not
                                        // know how much space it need to allocate
                                        // for the member
        
            // Some even more members...
        }
        // Now the compiler knows the full contents of the structure, its size
        // and alignment requirements
        ;
        

        【讨论】:

          猜你喜欢
          • 2012-12-12
          • 1970-01-01
          • 2019-01-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-12
          • 2018-09-11
          • 2019-07-09
          相关资源
          最近更新 更多