// 内存对齐.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

#pragma pack(8) //指定对齐值
struct example1
{
long b;
short c;
long d;
};
struct example2
{
char a;
example1 struct1;
short e;
};
#pragma pack() //取消指定对齐,恢复缺省对齐

int _tmain(int argc, _TCHAR* argv[])
{
example1 temp1;
example2 struct2;
memset(&temp1,0,sizeof(example1));
memset(&struct2,0,sizeof(example2));

cout << sizeof(temp1) << endl;
cout << sizeof(example2) << endl;
cout << (unsigned int)(&struct2.struct1) - (unsigned int)(&struct2) << endl;

return 0;
}

//1)数据类型自身的对齐值:就是上面交代的基本数据类型的自身对齐值。
//2)指定对齐值:#pragma pack (value)时的指定对齐值value。
//3)结构体或者类的自身对齐值:其成员中自身对齐值最大的那个值。
//4)数据成员、结构体和类的有效对齐值:自身对齐值和指定对齐值中较小的那个值。

//#pragma pack(2)
//10 //struct1.sizeof
//14 //struct2.sizeof
//+ &struct2 0x0042f8d0 {a=0 '\0' struct1={b=0 c=0 d=0 } e=0 } example2 *
//+ &struct2.a 0x0042f8d0 "" char *
//+ &struct2.struct1.b 0x0042f8d2 {0} long *
//+ &struct2.struct1.c 0x0042f8d6 {0} short *
//+ &struct2.struct1.d 0x0042f8d8 {0} long *
//+ &struct2.e 0x0042f8dc {0} short *
//+ &temp1 0x0042f8e8 {b=0 c=0 d=0 } example1 *
//+ &temp1.b 0x0042f8e8 {0} long *
//+ &temp1.c 0x0042f8ec {0} short *
//+ &temp1.d 0x0042f8ee {0} long *

//#pragma pack(5)
//warning C4086: expected pragma parameter to be '1', '2', '4', '8', or '16'
//12 //struct1.sizeof
//20 //struct2.sizeof
//+ &struct2 0x0022fa98 {a=0 '\0' struct1={b=0 c=0 d=0 } e=0 } example2 *
//+ &struct2.a 0x0022fa98 "" char *
//+ &struct2.struct1.b 0x0022fa9c {0} long *
//+ &struct2.struct1.c 0x0022faa0 {0} short *
//+ &struct2.struct1.d 0x0022faa4 {0} long *
//+ &struct2.e 0x0022faa8 {0} short *
//+ &temp1 0x0022fab4 {b=0 c=0 d=0 } example1 *
//+ &temp1.b 0x0022fab4 {0} long *
//+ &temp1.c 0x0022fab8 {0} short *
//+ &temp1.d 0x0022fabc {0} long *


//#pragma pack(6)
//12 //struct1.sizeof
//20 //struct2.sizeof
//+ &struct2 0x0046fcd4 {a=0 '\0' struct1={b=0 c=0 d=0 } e=0 } example2 *
//+ &struct2.a 0x0046fcd4 "" char *
//+ &struct2.struct1.b 0x0046fcd8 {0} long *
//+ &struct2.struct1.c 0x0046fcdc {0} short *
//+ &struct2.struct1.d 0x0046fce0 {0} long *
//+ &struct2.e 0x0046fce4 {0} short *
//+ &temp1 0x0046fcf0 {b=0 c=0 d=0 } example1 *
//+ &temp1.b 0x0046fcf0 {0} long *
//+ &temp1.c 0x0046fcf4 {0} short *
//+ &temp1.d 0x0046fcf8 {0} long *

//#pragma pack(8)
//12 //struct1.sizeof
//20 //struct2.sizeof
//+ &struct2 0x0020faec {a=0 '\0' struct1={b=0 c=0 d=0 } e=0 } example2 *
//+ &struct2.a 0x0020faec "" char *
//+ &struct2.struct1.b 0x0020faf0 {0} long *
//+ &struct2.struct1.c 0x0020faf4 {0} short *
//+ &struct2.struct1.d 0x0020faf8 {0} long *
//+ &struct2.e 0x0020fafc {0} short *
//+ &temp1 0x0020fb08 {b=0 c=0 d=0 } example1 *
//+ &temp1.b 0x0020fb08 {0} long *
//+ &temp1.c 0x0020fb0c {0} short *
//+ &temp1.d 0x0020fb10 {0} long *

 

posted on 2016-03-30 15:22  步天有术  阅读(246)  评论(0编辑  收藏  举报