考虑到这些结构:
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的第一个成员。
我在一个有效的代码库中发现了这一点,我只是想知道它是标准的还是有任何对齐问题。
答案 0 :(得分:5)
typedef union {
StructA a;
StructB b;
} Union;
a
与联合中的b
具有相同的偏移量:0
a
在StructB
中偏移0。
这些电话是等效的。