现在的位置: 首页 > 综合 > 正文

结构体成员的内存对齐

2013年09月16日 ⁄ 综合 ⁄ 共 1401字 ⁄ 字号 评论关闭
#include <iostream>
using namespace std;

//#pragma pack(1) //使用#pragma pack可以将对齐设置为1
/*
内存对齐的3个准则:
1、结构体变量的首地址能够被其最宽的基本类型成员大小所整除
2、结构体每个成员相对于结构体首地址的偏移量(offset)都是这个成员大小的整数倍,如有不足则补上
3、结构体总大小为结构体最宽的基本类型成员的整数倍
*/
struct widget1
{
	double d;		//sizeof(double)== 8
	int i;			//sizeof(int)	== 4
	short s;		//sizeof(short)	== 2
	char c;			//sizeof(char)	== 1

	static int count;	//count是静态成员,静态成员的空间不在类的实例中,
						//而是像全局变量一样在静态存储区,被类共享。
};
int widget1::count = 0;
/*
对于widget1:
d的偏移量为0;
i的偏移量为8,是sizeof(int)的整数倍,不需补字节
s的偏移量为8+4=12,是sizeof(short)的整数倍,不需补字节
c的偏移量为8+4+2=14,是sizeof(char)的整数倍,不需补字节
目前的结构体的字节数为8+4+2+1=15,不是最大基本变量d大小的整数倍,需要补上1字节,15+1=16
所以sizeof(widget1)==16
*/

struct widget2
{
	
	int i;			//sizeof(int)	== 4
	short s;		//sizeof(short)	== 2
	char c;			//sizeof(char)	== 1
	double d;		//sizeof(double)== 8
};
/*
对于widget2:
i的偏移量为0
s的偏移量为4,是sizeof(short)的整数倍,不需补字节数
c的偏移量为4+2=6,也不需补字节数
d的偏移量为4+2+1=7,但不是sizeof(double)的整数倍,要补字节数1,
所以d的偏移量为4+2+1+1(补齐)=8
目前结构体的字节数为4+2+1+1(补齐)+8=16,是最大基本变量d大小的整数倍,不需补齐
所以sizeof(widget2)==16
*/
struct widget3
{
	char c;			//sizeof(char)	== 1
	int i;			//sizeof(int)	== 4	
	short s;		//sizeof(short)	== 2
	double d;		//sizeof(double)== 8
};
/*
对于widget2:
c的偏移量为0
i的偏移量为1(c的大小)+3(补齐)=4
s的偏移量为1(c的大小)+3(补齐)+4(i的大小)=8
d的偏移量为1(c的大小)+1(补齐)+4(i的大小)+2(s的大小)+6(补齐)=16
目前结构体的大小为1(c的大小)+1(补齐)+4(i的大小)+2(s的大小)+6(补齐)+8(d的大小)=24,不需补齐
所以sizeof(widget3)=24
*/

int main()
{
	cout<<"the size of widget is: "<<sizeof(widget1)<<endl;
	cout<<"the size of widget is: "<<sizeof(widget2)<<endl;
	cout<<"the size of widget is: "<<sizeof(widget3)<<endl;
	system("pause");
	return 0;
}

抱歉!评论已关闭.