为什么
sizeof(A)
是12?
应该是:
float(4) + x_0-pad(2) + y_1(2) = 8
如果全部与
float
对齐,我该如何避免这种情况?
struct A
{
int x_0 : 1;
int x_1 : 1;
int x_2 : 1;
int x_3 : 2;
int x_4 : 2;
int x_5 : 2;
int x_6 : 3;
uint16_t pad : 4;
uint16_t y_1;
float y_2;
};
位字段没有存储空间,但它们的内存位置与您提供的标量类型大小相同,因此对齐通常至少具有相同的大小,但在遇到零大小的字段之前,不会定义 a 中的顺序- “相同类型的非零位域序列”。
在你的情况下,在小端系统上你的结构可能是这样组织的
<location #0> x_6 x_5 x_4 ... <location #1> x_3 x_2 x_1 x_0 ... <location #2> pad
或
<location #0> x_4 x_3 x_2 x_1 x_0 ... <location #1> x_6 x_5 ... <location #2> pad
但在大端或一些灵活的架构上它可以是
<location #0> ... x_0 x_1 x_2 x_3 x_4 <location #1> ... x_5 x_6 <location #2> pad
不同的类型导致需要考虑新的位置。您可以添加零大小的字段:
int x_break: 0;
打破顺序。由
...
标记的未使用位不被正式视为填充,但工作原理类似。
除非用户更改
struct
上的对齐要求,否则<location #2> pad
后会有填充以满足float
的对齐要求。
注意:您甚至不能保证位字段从结构的开头开始,仅保留与其他结构成员的一般顺序。