通过使用宏,指定某些结构体或者类的字节对齐方式.
#pragma pack(push) //让原字节对齐方式入编译器栈
#pragma pack(1) //指定新的对齐方式, 1字节对齐. (数字即几字节对齐)
//这里面放置你需要指定1字节对齐的结果体或者类
struct {};
struct{};
#pragma pack(pop)//出栈原来对齐方式
来自MSDN的例子:
struct S { int i; // size 4 short j; // size 2 double k; // size 8 }; #pragma pack(2) struct T { int i; short j; double k; }; int main() { printf("%d ", offsetof(S, i)); printf("%d ", offsetof(S, j)); printf("%d\n", offsetof(S, k)); T tt; printf("%d ", offsetof(T, i)); printf("%d ", offsetof(T, j)); printf("%d\n", offsetof(T, k)); }
输出:
0 4 8 0 4 6