为什么VC编译pragma pack(show)显示8?
我在32位下编译一个helloworld程序,工程设置都是默认。代码里面加入一句:
#pragma pack(show)
竟然打印8.
应该是4才对啊,32位下按照4个自己的倍数对齐,就像我下面这个程序:
- C/C++ code
#pragma pack (show) struct ss{ short s; int i; int ii; }; int main(void) { ss obj[2]; printf("%d,%d\n",sizeof(size_t),sizeof(ss)); printf("%p,%p\n",&obj[0],&obj[1]); return 0; }
这里sizeof(ss)=12,且obj[0]和obj[1]地址相差12.
为什么MSDN上面写:
n(optional)
Specifies the value, in bytes, to be used for packing. The default value for n is 8. Valid values are 1, 2, 4, 8, and 16. The alignment of a member will be on a boundary that is either a multiple of n or a multiple of the size of the member, whichever is smaller.
n can be used with push or pop for setting a particular stack value, or alone for setting the current value used by the compiler.
[解决办法]
上面这句话已经写得很清楚了:
The alignment of a member will be on a boundary that is either a multiple of n or a multiple of the size of the member, whichever is smaller.
pack=min(n,max(成员的大小))