微軟官方文檔說#pragma pack
指令的作用是爲結構、聯合和類成員指定 pack 對齊。的主要作用就是改變編譯器的內存對齊方式,這個指令在網絡報文的處理中有着重要的作用,#pragma pack(n)
是他最基本的用法,其作用是改變編譯器的對齊方式, 不使用這條指令的情況下,編譯器默認採取#pragma pack(8)
也就是8字節的默認對齊方式,n值可以取1, 2, 4, 8, 16
中任意一值。
來寫一個程序試下:
#include <iostream>
#include <stddef.h>
using namespace std;
struct Test{
short a;//2
int b;//4
double c;//8
long d;//8
};
#pragma pack(2)
struct S {
short a;//2
int b;//4
double c;//8
long d;//8
};
int main()
{
cout << offsetof(Test, a) << endl;
cout << offsetof(Test, b) << endl;
cout << offsetof(Test, c) << endl;
cout << offsetof(Test, d) << endl;
cout << "---------------" << endl;
cout << offsetof(S, a) << endl;
cout << offsetof(S, b) << endl;
cout << offsetof(S, c) << endl;
cout << offsetof(S, d) << endl;
system("pause");
return 0;
}
該程序在win32位PC機下打印結果如下:
0
4
8
16
---------------
0
2
6
14