2016-09-22 14 views
1

AAの定義があります。2 structがあります。私はstruct APOINTERが含まれているが、構造体の定義は、閉じ中括弧まで終了していないのでstruct Astruct A(ないポインタ)"struct inside struct"の制限

+1

私はこの質問に行くでしょう - おそらく手に入れる辞書を持っています –

+0

あなたの質問をよく理解しないでください –

+1

[struct inside struct]の可能な複製(http://stackoverflow.com/questions/14040612/) struct-inside-struct) – Olaf

答えて

1

が含まれていることができない理由を私は理解していないstruct AにOKがあることを知っています}。構造体メンバを宣言するためには、コンパイラは完全な定義を必要とします。その情報を使用してスペースやパディング、アラインメントなどを計算する必要があります。ポインタのサイズはポインタのサイズであり、タイプの名前であり、完全な定義ではありません。それは再帰的に独自のタイプのデータメンバーを格納しなければならないように、その場合には、それは無限のストレージを取るため

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):不可能です。

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を含み、もう一つのAはintともう一つのAを含んでいます。そして、あなたはintの無限の数を持っています。

+0

これといくつかの矛盾が修正されました。ありがとうございます。 – Mike