各成員變量存放的起始地址相對於結構的起始地址的偏移量必須爲該變量的類型所佔用的字節數的倍數, 各成員變量在存放的時候根據在結構中出現的順序依次申請空間 同時按照上面的對齊方式調整位置。 空缺的字節自動填充, 同時爲了確保結構的大小爲結構的字節邊界數(即該結構中佔用最大的空間的類型的字節數)的倍數,因此在爲最後一個成員變量申請空間後 還會根據須要自動填充空缺的字節;ios
#include <iostream> using namespace std; #pragma pack(8) struct Test1 { char a; //0 - 1 short b;//2 - 3 int c;// 4 - 7 float d;//8 - 11 double e;//12 - 23 }; #pragma pack(4) struct Test2 { char a; //0 - 1 short b;//2 - 3 int c;// 4 - 7 float d;//8 - 11 double e;//12 - 19 }; #pragma pack(8) struct Test3 { double e;//0-7 float d;//8-13 short b;//14-15 int c;// 16-19 char a; //20-23 }; int main() { std::cout << "size test1= " << sizeof(Test1) << std::endl; std::cout << "size test2= " << sizeof(Test2) << std::endl; std::cout << "size test3= " << sizeof(Test3) << std::endl; return 0; }