#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字节。