内存对齐规则

  1. 结构体(struct)/联合体(union)里的数据成员:第一个数据成员放在offset为0的地方,以后每个数据成员存储的起始位置要从该成员大小的整数倍开始。
  2. 结构体作为成员:如果一个结构里有某些结构体成员,则结构体成员要从其内部最大元素大小的整数倍地址开始存储。
  3. 结构体的总大小对齐:也就是sizeof的结果,必须是其内部最大成员的整数倍,不足的要补齐。
VS2013 + WIN7_64
char = 1
short = 2
int = 4
long = 4
float = 4
double = 8


实例:
#include <iostream>
using namespace std;

typedef struct StuInfo
{
	int id;//4个字节,0 - 3
	double weight;//8个字节,8 - 15
	float height;//4个字节,16 - 19
	//整体对齐4 * 5 = 20
}StuInfo;

typedef struct Stu
{
	char name[2];//2个字节,0 - 1
	int id;//4个字节,4 - 7
	double score;//8个字节,8 - 15
	short grade;//2个字节,16 - 17
	StuInfo c;//24个字节,24 - 47
}Stu;

int main(void)
{

	cout << "StuInfo = " << sizeof(StuInfo) << endl;
	cout << "Stu = " << sizeof(Stu) << endl;
	
	
	/*
	cout << "char = " << sizeof(char) << endl;
	cout << "short = " << sizeof(short) << endl;
	cout << "int = " << sizeof(int) << endl;
	cout << "long = " << sizeof(long) << endl;
	cout << "float = " << sizeof(float) << endl;
	cout << "double = " << sizeof(double) << endl;
	*/
	return 0;
}


输出:
StuInfo = 24
Stu = 48

--------------------------------------------------------------------------------------------------
当我们在VS设置#pragma pack(1)时,是在告诉编译器,所有的对齐都是按照1的整数倍,即不采用内存对齐规则。所以以上输出为:
StuInfo = 16
Stu = 32

#pragma pack(4) ---->所有的对齐都是按照4的整数倍

#pragma pack(4)
#include <iostream>
using namespace std;

typedef struct StuInfo
{
	int id;//4个字节,0 - 3
	double weight;//8个字节,4 - 11
	float height;//4个字节,12 - 15
}StuInfo;//16个字节

typedef struct Stu
{
	char name[2];//2个字节,0 - 1
	int id;//4个字节,4 - 7
	double score;//8个字节,8 - 15
	short grade;//2个字节,16 - 17
	StuInfo c;//16个字节,20 - 35
}Stu;//36个字节

int main(void)
{

	cout << "StuInfo = " << sizeof(StuInfo) << endl;
	cout << "Stu = " << sizeof(Stu) << endl;
	
	
	/*
	cout << "char = " << sizeof(char) << endl;
	cout << "short = " << sizeof(short) << endl;
	cout << "int = " << sizeof(int) << endl;
	cout << "long = " << sizeof(long) << endl;
	cout << "float = " << sizeof(float) << endl;
	cout << "double = " << sizeof(double) << endl;
	*/
	return 0;
}
输出:
StuInfo = 16
Stu = 36




Keep it simple!
作者:N3verL4nd
知识共享,欢迎转载。
原文地址:https://www.cnblogs.com/lgh1992314/p/6616349.html