C中的联合使用是否有效/合规?

时间:2017-02-11 15:50:19

标签: c struct unions

考虑到这些结构:

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的第一个成员。

我在一个有效的代码库中发现了这一点,我只是想知道它是标准的还是有任何对齐问题。

1 个答案:

答案 0 :(得分:5)

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

a与联合中的b具有相同的偏移量:0

aStructB中偏移0。

这些电话是等效的。

相关问题