您的位置:首页 > 编程语言 > C语言/C++

C++高效编程笔记2:struct中的字节对齐

2007-01-13 14:56 507 查看
#include <iostream.h>

structA{
chara;longb;charc;longd;
};
structB{
chara;charc;longb;longd;
};

#pragma pack(push, 1)
structC{
chara;longb;charc;longd;
};
#pragma pack(pop)

structD{
char*a;char*b;
};
//使用比特域的结构
structBitField{
unsigneda1:11; //long 1
unsigneda2:11;
unsignedb1:10;
unsigneda3:11; //long 2
unsigneda4:11;
unsignedb2:10;
};

voidmain(void)
{
cout<<"Size of A : "<<sizeof(A)<<"bytes"<<endl;
cout<<"Size of B : "<<sizeof(B)<<"bytes"<<endl;
cout<<"Size of C : "<<sizeof(C)<<"bytes"<<endl;
cout<<"Size of D : "<<sizeof(D)<<"bytes"<<endl;
cout<<"Size of BitField : "<<sizeof(BitField)<<"bytes"<<endl;
}

运行结果:

Size of A : 16bytes
Size of B : 12bytes
Size of C : 10bytes
Size of D : 8bytes
Size of BitField : 8bytes
A、B、C之所以不一样是因为字节对齐的问题。#pragma pack(push, 1)指令可以让编译器暂时调整对齐,设置为1字节。
另外注意,char * 一般占4字节。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: