2017-02-11 49 views
8

鑑於這些結構:C有效/符合工會的這種使用?

typedef struct { 
    //[...] 
} StructA; 

typedef struct { 
    StructA a; 
    //[...] 
} StructB; 

typedef union { 
    StructA a; 
    StructB b; 
} Union; 

低於等同,而不是不確定的兩種接入方式?

Union u; 
memcpy(&u.b, /*...*/); //Pretend I populated StructB here 
u.a; // Method 1 
u.b.a; // Method 2 

請注意StructA碰巧是StructB的第一個成員。

我在代碼庫中發現了這個問題,我只是想知道它是標準還是有任何對齊問題。

回答

5
typedef union { 
    StructA a; 
    StructB b; 
} Union; 

a具有相同的在聯合作爲b偏移量:0

aStructB偏移0。

呼叫是等同的。

相關問題