//测试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));
}