C++技巧:通过pragmapack(n)改变字节对齐
通过#pragma pack(n)改变C编译器的字节对齐方式。在C语言中,structure是一种复合数据类型,其组成元素可以是基本数据类型的变量(如int、long、float等。)或某些复合数据类型的数据单元(如数组、结构、并集等。).在结构中,编译器根据结构的自然对齐条件为每个成员分配空。看下面这个例子。
其输出为:
sizeof(char)= 1 sizeof(int)= 4 sizeof(short)= 2 sizeof(Long)= 4
struct 1(char,int,short,long) offset: 0 4 8 12 sizeof(my struct 1)= 16
struct 2(char,int,short,Long)offset:0 2 6 8 sizeof(my struct 2)= 12
struct 3(char,int,short,Long)offset:0
短c;
long d;
};
/*2字节对齐*/
# pragma pack(2)
struct my struct 2 {
char a;
int b;
短c;
long d;
};
/*1字节对齐*/
# pragma pack(1)
struct mystruct 3 {
char a;
int b;
短c;
long d;
};
/*还原默认字节对齐*/
# pragma pack()
struct my struct 4 {
char a;
int b;
短c;
long d;
};
int main(int argc,char * argv[]){
int a _ off;
int b _ off;
int c _ off;
int d _ off;
struct my struct 1 S1;
struct my struct 2 S2;
struct my struct 3 S3;
struct my struct 4 S4;
printf(" sizeof(char)= % d sizeof(int)= % d sizeof(short)= % d sizeof(long)= % d \ n ",
sizeof(char),sizeof(int),sizeof(short),sizeof(long));
/* my struct 1 */
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 ",a_off,b_off,c_off,d _ off);
printf(" sizeof(my struct 1)= % d \ n ",sizeof(my struct 1));
/* my struct 2 */
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 ",a_off,b_off,c_off,d _ off);
printf(" sizeof(my struct 2)= % d \ n ",sizeof(my struct 2));
/* my struct 3 */
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 ",a_off,b_off,c_off,d _ off);
printf(" sizeof(my struct 3)= % d \ n ",sizeof(my struct 3));
/* my struct 4 */
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 ",a_off,b_off,c_off,d _ off);
printf(" sizeof(my struct 3)= % d \ n ",sizeof(my struct 4));
返回0;
}
0条评论