结构体需要根据数据类型进行内存对齐。
所有数据类型占据空间的大小,一定是它基础类型的倍数。
首先按照最大的数据类型格式来作为最小分割单元。
最大整数倍
struct stu
{
	char gender;
	unsigned int age;
}student1;
int main()
{
	printf("sizeof this struct is %d。\n", sizeof(student1));
	getchar();
	return 0;
} 

最大的数据类型是int,占据4个字节。然后首先age,占满第一个4字节分割单元。
然后char gender,1个字节,也要占据一个4字节大小的分割字节。不满也是一个分割单元。
所以整体占据8字节。
顺序分配
struct stu
{
	char name[20];    // 20
	unsigned int age; // 4
	char tel[15];     // 15
	float scores[3];  // 12  
	char gender;      // 1        // 20 + 4 + 15 + 12 + 1 = 52
}student1;
int main()
{
	printf("sizeof this struct is %d。\n", sizeof(student1));
	getchar();
	return 0;
} 


基础内存分割(对齐)单元,根据最大基础类型确认。当前为int,4字节。
- char name[20]为20字节,占满5个单元。20个字节。
 - unsigned int age为4字节,占满1个单元。4个字节。
 - char tel[15]为15字节,占4个单元,最后一个单元差一个字节占满。看做占用16字节。
 - float score[3]为3个4字节的float。占满3个单元。 占用12个字节。
 - char gender虽然只占一个字节,但是单独开辟了一个分割单元。因此看做占据4字节
 
- 20 + 4 + 16 + 12 + 4 = 56字节。
 
优化内存

将gender上移一行。快捷键Alt + 向上箭头。
struct stu
{
	char name[20];    // 20
	unsigned int age; // 4
	char tel[15];     // 15
	char gender;      // 1        // 20 + 4 + 15 + 12 + 1 = 52
	float scores[3];  // 12  
}student1; 
此时由56变为52。
所以写结构体的一般建议:按照数据类型,从大到小往下写。
例如:
struct stu
{
	char* p;   // 4
	char arr[2];  // 2
	int c;   // 4
	short d; // 2
	double f;  // 8
	long g;   // 4
	float h[2]; // 8
}student1;
int main()
{
	printf("sizeof this struct is %d。\n", sizeof(student1));
	getchar();
	return 0;
} 

输出为40个字节;
但是我们优化一下;按照从大到小往下写:
struct stu
{
	float h[2]; // 8
	double f;  // 8
	char* p;   // 4
	int c;   // 4
	long g;   // 4
	char arr[2];  // 2
	short d; // 2
}student1;
int main()
{
	printf("sizeof this struct is %d。\n", sizeof(student1));
	getchar();
	return 0;
} 
输出32个字节。

但是这样的问题是:可能结构体的顺序不利于大部分场景下的代码阅读。
这也是一种tradeoff。


















