“struct inside struct”中的限制

时间:2016-09-22 19:38:21

标签: c struct

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

4 个答案:

答案 0 :(得分:5)

因为当你将结构放在彼此内部时,你会在那时将该结构的另一个副本放入结构中。例如:

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。

答案 1 :(得分:3)

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

答案 2 :(得分:1)

因为在结束大括号}之前结构定义尚未完成。要声明一个结构成员,编译器需要完整的定义,因为它使用该信息来计算诸如空间,填充和对齐等内容。对于指向某事物的指针,指针的大小是指针的大小,以及所有编译器需要的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
;

答案 3 :(得分:1)

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

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

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