在 previous question 中, 我 learned当一个具有 8 字节对齐的结构嵌入另一个具有 4 字节对齐的结构时,需要在 8 字节对齐的结构之前进行填充。
明白了。
至少我认为我理解了。
For structures, unions, and arrays, the alignment-requirement is the largest alignment-requirement of its members.
所以,如果我有这样的结构:
typedef struct s_inner {
unsigned long ul1;
double dbl1;
fourth_struct s4;
unsigned long ul2;
int i1;
} t_inner;
我希望这个结构的所有成员都是 8 字节对齐的,因为 double
是 8 字节对齐的。
但是我的内存转储显示了这个:
t_inner
从地址 1B8
开始:
1B8
:unsigned long
被填充,因为该结构是 8 字节对齐的1C0
:double
占用 8 个字节1C8
:后面是fourth_struct
,它有4字节对齐
到现在为止,一切都如期而至。但是现在 t_inner
中的对齐切换:
在地址 1E8
上,我希望在这里找到 unsigned long
,用 4 个字节填充,以便下面的 int
也对齐8 个字节。但似乎对齐已经改变,因为 unsigned long
不携带填充字节。相反,以下 int
以 4 字节对齐方式放置。
为什么对齐方式会在 t_inner
内切换?这里应用了哪条规则?
最佳答案
I'd expect all members of this structure would be 8-byte aligned since the double is 8-byte > aligned.
嗯,不。每个类型在结构内部都有自己的对齐方式,结构本身有一个最大的对齐方式它的内容对齐方式。
aligned. typedef struct s_inner {
unsigned long ul1; // 4-aligned
double dbl1; // 8-aligned (need 4 padding before this)
fourth_struct s4; // 4 aligned size 32
unsigned long ul2; // 4 aligned (no padding)
int i1; // 4 aligned (no padding)
// no padding needed as struct is a multiple of 8 bytes
} t_inner;
由于 double ,结构本身对齐 8。
关于c - 为什么内存对齐会在结构内发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27858493/