// 111.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
/*
编译器内存字节对齐的原则
1. 数据类型的自身对齐值
数据类型的自身对齐值:其在内存中所占的字节数,如在32位系统中,char为1字节,short为2字节,int、float、double、long为4字节。
2. 结构体或类的自身对齐值
结构体或类的自身对齐值:其成员中自身对齐值最大的那个值。
3. 默认对齐值
结构体或类的默认对齐值为其成员中自身对齐值最大的那个值。
4. 指定对齐值
使用#pragma pack(value)时指定的值value。
5. 结构体和类的有效对齐值
结构体和类的有效对齐值为:没有指定对齐值时为默认对齐值和自身对齐值的最小值;当指定了对齐值后为指定对齐值和自身对齐值的最小值。
对于一个结构体,不但需要对其每个成员变量进行内存地址对齐,还要对结构体本身进行对齐。
具体规则是:在假设结构体起始地址为0x0000的情况下,要求各成员变量的起始地址必须是其相应有效对齐值的整数倍,
并要求结构体的大小也为该结构体有效对齐值的整数倍。
*/
struct Test
{
int a; //(4,4) = 4, 各成员变量的起始地址必须是其相应有效对齐值的整数倍 0x00 % 4 = 0;
char b; //(1,4) = 4, 0x04 % 1 = 0;
short c;//(2,4) = 4, 0x06 % 1 = 0;
};//struct(Test) = Max(4,1,2) = 4; 0x08 % 3 = 0;
struct Test2
{
char b;
short c;
int a;
};
struct Test3
{
char b; //(1,4) = 1 0x00 % 1 = 0;
int a; //(4,4) = 4; 因为各成员变量的起始地址必须是其相应有效对齐值的整数倍所以这里的开始地址 0x02,0x03,0x01都不符合,0x04 % 4 = 0;
short c;//(2,4) = 2; 0x08 %2 = 0;
//struct(Test3) = Max(1,4,2) = 4; 0x12 % 4 = 0
};
int main(int argc, char* argv[])
{
cout<<sizeof(Test)<<endl;//8
cout<<sizeof(Test2)<<endl;//8
Test test;
cout<<sizeof(test)<<endl;
cout<<sizeof(Test3)<<endl;//12
printf("Hello World!\n");
return 0;
}
原文:http://blog.csdn.net/djb100316878/article/details/41673743