// 內存對齊.cpp : Defines the entry point for the console application.
//ios
#include "stdafx.h"
#include <iostream>
using namespace std;app
#pragma pack(8) //指定對齊值
struct example1
{
long b;
short c;
long d;
};
struct example2
{
char a;
example1 struct1;
short e;
};
#pragma pack() //取消指定對齊,恢復缺省對齊spa
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;io
return 0;
}console
//1)數據類型自身的對齊值:就是上面交代的基本數據類型的自身對齊值。
//2)指定對齊值:#pragma pack (value)時的指定對齊值value。
//3)結構體或者類的自身對齊值:其成員中自身對齊值最大的那個值。
//4)數據成員、結構體和類的有效對齊值:自身對齊值和指定對齊值中較小的那個值。stream
//#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 *gc
//#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 *