1. 程式人生 > >測試VC++結構成員對齊的問題

測試VC++結構成員對齊的問題

//測試VC++  結構成員對齊的問題 by zdleek

//一下結論通過VC2008編譯測試得來

void TestStructMemberAlig()

{

#pragma pack(push, 8)
 struct   MyStructure
 {
  double i1;
  char   a1;
  char   a2;
  char   a3;
  double i2;
  char   a4[2];
 }s1;
#pragma pack(pop)


 //上述結構成員對齊為8位元組(Bytes),
 //double i1佔8位元組, 那麼成員變數a1,a2,a3之後且i2之前,VC++會增加5個位元組補足對齊( 3 + 5 = 8 bytes )
 //同樣,成員變數a4之後會補6個位元組用於對齊
 //這樣sizeof(s1)的大小實際上是sizeof(double) + sizeof(a1,a2,a3,a4) + 5 + 6 = 16 + 5 + 5 + 6 = 32;


 int i = sizeof(s1);
 s1.i1 = 1;
 s1.a1 = 'a';
 s1.a2 = 'a';
 s1.a3 = 'a';
 s1.i2 = 1;
 s1.a4[0] = 'c';
 s1.a4[1] = 'c';
 int d = sizeof(double);
 double dbl = s1.i2;
 char buf[50] ={0};
 memset(buf, -1, sizeof(buf));
 memcpy(buf, &s1, sizeof(s1)); //注意在debug狀態下檢視buf的內容,可以驗證結構成員補齊是如何補齊的
 
#pragma pack(push, 1)
 struct   MyStructure2
 {
  double i1;
  char   a1;
  char   a2;
  char   a3;
  double i2;
  char   a4[2];
 }s2;
#pragma pack(pop)

 s2.i1 = 2;
 s2.a1 = 'c';
 s2.a2 = 'c';
 s2.a3 = 'c';
 s2.a4[0] = 'c';
 s2.a4[1] = 'c';
 s2.i2 = 2;
 int i2 = sizeof(s2);
 double dbl2 = s2.i2;
 char buf2[50] ={0};
 memset(buf2, -1, sizeof(buf2));

//注意在debug狀態下檢視buf的內容,可以驗證結構成員補齊是如何補齊的

//(對齊是1個位元組,則結構成員當中不會有額外的位元組補齊)
 memcpy(buf2, &s2, sizeof(s2));

}