为了让CPU能够更舒服地访问到变量,struct中的各成员变量的存储地址有一套对齐的机制。这个机制概括起来有两点:第一,每个成员变量的首地址,必须是它的类型的对齐值的整数倍,如果不满足,它与前一个成员变量之间要填充(padding)一些无意义的字节来满足;第二,整个struct的大小,必须是该struct中所有成员的类型中对齐值最大者的整数倍,如果不满足,在最后一个成员后面填充。
各种类型的变量的align值如下,参考的是wikipedia的页面:Data structure alignment
The following typical alignments are valid for compilers from Microsoft, Borland, and GNU when compiling for 32-bit x86:
A char (one byte) will be 1-byte aligned.
A short (two bytes) will be 2-byte aligned.
An int (four bytes) will be 4-byte aligned.
A float (four bytes) will be 4-byte aligned.
A double (eight bytes) will be 8-byte aligned on Windows and 4-byte aligned on Linux.
A long double (twelve bytes) will be 4-byte aligned on Linux.
Any pointer (four bytes) will be 4-byte aligned on Linux. (eg: char*, int*)
The only notable difference in alignment for a 64-bit linux system when compared to a 32 bit is:
A double (eight bytes) will be 8-byte aligned.
A long double (Sixteen bytes) will be 16-byte aligned.
Any pointer (eight bytes) will be 8-byte aligned.
struct s {
char a; //在地址为0的位置
char padding1[1]; //由于下面一个元素是short,对齐字节数为2的位数,需要补1字节
short b; //对齐到了地址为2的位置
char c; //在地址为4的位置
char padding2[3]; //由于下面一个元素是double,对齐字节数为8的倍数,需要补3字节
double d; //对齐到了地址为8的位置
char e; //在地址为16的位置
char padding3[7]; //整个struct的大小需要是对齐数最大者,也就是double的8字节的整数倍
};