#pragma pack
Visual C++中对齐的范围是什么?API 参考
https://msdn.microsoft.com/en-us/library/vstudio/2e70t5y1%28v=vs.120%29.aspx
说:
pack 在看到 pragma 后的第一个结构、联合或类声明时生效
因此,对于以下代码:
#include <iostream>
#pragma pack(push, 1)
struct FirstExample
{
int intVar; // 4 bytes
char charVar; // 1 byte
};
struct SecondExample
{
int intVar; // 4 bytes
char charVar; // 1 byte
};
void main()
{
printf("Size of the FirstExample is %d\n", sizeof(FirstExample));
printf("Size of the SecondExample is %d\n", sizeof(SecondExample));
}
我已经预料到:
Size of the FirstExample is 5
Size of the SecondExample is 8
但我收到了:
Size of the FirstExample is 5
Size of the SecondExample is 5
这就是为什么我有点惊讶,我非常感谢你能提供的任何解释。