#pragma pack() 字节对齐
//2007.1.18 字节对齐
#pragma pack(4)
typedef struct _ST001
{
int aa; //0-3
char a;//1:4 按1字节对齐,4
int b; //4:4 按4字节对齐,
char c;//2:4 按2字节对齐
}ST001;
class C001
{
public:
int aa;
char a;//1:4 按1字节对齐
int b; //4:4 按4字节对齐
char c;//2:4 按2字节对齐
};
#pragma pack()
typedef struct _ST002
{
int aa;
char a;
int b;
char c;
}ST002;
class C002
{
public:
int aa;
char a;//1:4 按1字节对齐
int b; //4:4 按4字节对齐
char c;//2:4 按2字节对齐
};
main()
{
//2007.1.18 字节对齐
printf("Struct:%d,%d\nClass:%d,%d",sizeof(ST001),sizeof(ST002),sizeof(C001),sizeof(C002));
getch();
}
输出结果:
Struct:16,16
Class:16,16
如改为#pragma pack(2)
输出结果为:
Struct:12,16
Class:12,16
测试环境:VC6,默认对齐:8
#pragma pack(4)
typedef struct _ST001
{
int aa; //0-3
char a;//1:4 按1字节对齐,4
int b; //4:4 按4字节对齐,
char c;//2:4 按2字节对齐
}ST001;
class C001
{
public:
int aa;
char a;//1:4 按1字节对齐
int b; //4:4 按4字节对齐
char c;//2:4 按2字节对齐
};
#pragma pack()
typedef struct _ST002
{
int aa;
char a;
int b;
char c;
}ST002;
class C002
{
public:
int aa;
char a;//1:4 按1字节对齐
int b; //4:4 按4字节对齐
char c;//2:4 按2字节对齐
};
main()
{
//2007.1.18 字节对齐
printf("Struct:%d,%d\nClass:%d,%d",sizeof(ST001),sizeof(ST002),sizeof(C001),sizeof(C002));
getch();
}
输出结果:
Struct:16,16
Class:16,16
如改为#pragma pack(2)
输出结果为:
Struct:12,16
Class:12,16
测试环境:VC6,默认对齐:8
浙公网安备 33010602011771号