通过#pragma pack(n)改变C编译器的字节对齐方式,在C语言中,结构是一种复合数据类型,其构成元素既可以是基本数据类型(如int、long、float等)的变量,也可以是一些复合数据类型(如数组、结构、联合等)的数据单元。在结构中,编译器为结构的每个成员按其自然对界(alignment)条件分配空间。看下面例子。 其输出是: 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; }
|