一、 C语言字节对齐问题
https://www.cnblogs.com/clover-toeic/p/3853132.html
二、结构体对齐准则
先来看四个重要的基本概念:
- 数据类型自身的对齐值:char型数据自身对齐值为1字节,short型数据为2字节,int/float型为4字节,double型为8字节。
- 结构体或类的自身对齐值:其成员中自身对齐值最大的那个值。
- 指定对齐值:#pragma pack (value)时的指定对齐值value。
- 数据成员、结构体和类的有效对齐值:自身对齐值和指定对齐值中较小者,即有效对齐值=min{自身对齐值,当前指定的pack值}。
三、共同体的sizeof也要考虑对齐
union
{
int a;
char b[6];
}u1;
int main()
{
printf("sizeof(u1) = %d\n", sizeof(u1));
return 0;
}
sizeof(u1) = 8
四、单独数据在内存中的存储按照数据本身的对齐
其实内存可以当作1个大结构体
int main()
{
int a;
char b;
char c1, c2;
short d1, d2;
printf("%#x\n", &a);
printf("%#x\n", &b);
printf("%#x\n", &c1);
printf("%#x\n", &c2);
printf("%#x\n", &d1);
printf("%#x\n", &d2);
return 0;
}
0x9352d158
0x9352d157
0x9352d156
0x9352d155
0x9352d152
0x9352d150
五、_attribute_((_packed_))
struct stru1
{
int a;
char b;
short c;
char d;
};
struct stru2
{
int a;
char b;
short c;
char d;
char e;
}__attribute__((__packed__));
int main()
{
stru1 s1, s2;
stru2 s3, s4;
cout << "sizeof(stru1) = " << sizeof(stru1) << endl;
cout << "sizeof(stru2) = " << sizeof(stru2) << endl;
cout << "---------------" << endl;
cout << "&s1 = " << (unsigned long*)&s1 << endl;
cout << "&s2 = " << (unsigned long*)&s2 << endl;
cout << "&s3 = " << (unsigned long*)&s3 << endl;
cout << "&s4 = " << (unsigned long*)&s4 << endl;
return 0;
}
sizeof(stru1) = 12
sizeof(stru2) = 9
---------------
&s1 = 0x7fff8206d9e0
&s2 = 0x7fff8206d9f0
&s3 = 0x7fff8206d9c0
&s4 = 0x7fff8206d9d0