新鲜、有趣,互联生活。令狐葱。

2007/01/13

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

#include <iostream.h>

struct A {
    char a; long b; char c; long d;
};
struct B {
    char a; char c; long b; long d;
};

#pragma pack(push, 1)
struct C {
    char a; long b; char c; long d;
};
#pragma pack(pop)

struct D {
    char *a; char *b;
};
//使用比特域的结构
struct BitField {
    unsigned a1 : 11;  //long 1
    unsigned a2 : 11;
    unsigned b1 : 10;
    unsigned a3 : 11;  //long 2
    unsigned a4 : 11;
    unsigned b2 : 10;
};

void main(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字节。

1 条评论:

ace 说...

你好能把你的blog模板发给偶么:oicq2005#gmail.com