这是在 C valid/compliant 中使用联合吗?
Is this use of unions in C valid/compliant?
给定这些结构:
typedef struct {
//[...]
} StructA;
typedef struct {
StructA a;
//[...]
} StructB;
typedef union {
StructA a;
StructB b;
} Union;
下面两种访问方式是等价的,不是undefined吗?
Union u;
memcpy(&u.b, /*...*/); //Pretend I populated StructB here
u.a; // Method 1
u.b.a; // Method 2
请注意,StructA 恰好是 StructB 的第一个成员。
我在一个有效的代码库中发现了这个,我只是想知道它是否是标准的,或者是否存在任何对齐陷阱。
typedef union {
StructA a;
StructB b;
} Union;
a
与联合中的 b
具有相同的偏移量:0
a
在 StructB
中的偏移量为 0。
调用是等价的。
给定这些结构:
typedef struct {
//[...]
} StructA;
typedef struct {
StructA a;
//[...]
} StructB;
typedef union {
StructA a;
StructB b;
} Union;
下面两种访问方式是等价的,不是undefined吗?
Union u;
memcpy(&u.b, /*...*/); //Pretend I populated StructB here
u.a; // Method 1
u.b.a; // Method 2
请注意,StructA 恰好是 StructB 的第一个成员。
我在一个有效的代码库中发现了这个,我只是想知道它是否是标准的,或者是否存在任何对齐陷阱。
typedef union {
StructA a;
StructB b;
} Union;
a
与联合中的 b
具有相同的偏移量:0
a
在 StructB
中的偏移量为 0。
调用是等价的。