![]() ![]() |
|
C++技巧:通过pragmapack(n)改变字节对齐 | |
作者:佚名 文章来源:不详 点击数 更新时间:2008/10/22 21:33:32 文章录入:杜斌 责任编辑:杜斌 | |
|
|
其输出是: sizeof(char)=1 sizeof(int)=4 sizeof(short)=2 sizeof(long)=4 struct1(char,int,short,long) offset: 0 4 8 12 sizeof(mystruct1)=16 struct2(char,int,short,long) offset: 0 2 6 8 sizeof(mystruct2)=12 struct3(char,int,short,long) offset: 0 1 5 7 sizeof(mystruct3)=11 struct3(char,int,short,long) offset: 0 4 8 12 sizeof(mystruct3)=16 #include /*默认字节对齐*/ struct mystruct1{ char a; int b; short c; long d; }; /*2字节对齐*/ #pragma pack(2) struct mystruct2{ char a; int b; short c; long d; }; /*1字节对齐*/ #pragma pack(1) struct mystruct3{ char a; int b; short c; long d; }; /*恢复默认字节对齐*/ #pragma pack() struct mystruct4{ char a; int b; short c; long d; }; int main(int argc,char* argv[]){ int a_off; int b_off; int c_off; int d_off; struct mystruct1 s1; struct mystruct2 s2; struct mystruct3 s3; struct mystruct4 s4; printf("sizeof(char)=%d sizeof(int)=%d sizeof(short)=%d sizeof(long)=%d\n", sizeof(char), sizeof(int), sizeof(short), sizeof(long)); /*mystruct1*/ a_off = (char*)&(s1.a) - (char*)&s1; b_off = (char*)&(s1.b) - (char*)&s1; c_off = (char*)&(s1.c) - (char*)&s1; d_off = (char*)&(s1.d) - (char*)&s1; printf("struct1(char,int,short,long) offset: %d %d %d %d",a_off,b_off,c_off,d_off); printf(" sizeof(mystruct1)=%d\n",sizeof(mystruct1)); /*mystruct2*/ a_off = (char*)&(s2.a) - (char*)&s2; b_off = (char*)&(s2.b) - (char*)&s2; c_off = (char*)&(s2.c) - (char*)&s2; d_off = (char*)&(s2.d) - (char*)&s2; printf("struct2(char,int,short,long) offset: %d %d %d %d",a_off,b_off,c_off,d_off); printf(" sizeof(mystruct2)=%d\n",sizeof(mystruct2)); /*mystruct3*/ a_off = (char*)&(s3.a) - (char*)&s3; b_off = (char*)&(s3.b) - (char*)&s3; c_off = (char*)&(s3.c) - (char*)&s3; d_off = (char*)&(s3.d) - (char*)&s3; printf("struct3(char,int,short,long) offset: %d %d %d %d",a_off,b_off,c_off,d_off); printf(" sizeof(mystruct3)=%d\n",sizeof(mystruct3)); /*mystruct4*/ a_off = (char*)&(s4.a) - (char*)&s4; b_off = (char*)&(s4.b) - (char*)&s4; c_off = (char*)&(s4.c) - (char*)&s4; d_off = (char*)&(s4.d) - (char*)&s4; printf("struct3(char,int,short,long) offset: %d %d %d %d",a_off,b_off,c_off,d_off); printf(" sizeof(mystruct3)=%d\n",sizeof(mystruct4)); return 0; } |
|
![]() ![]() |