结构体概念
- 结构体属于用户自定义的数据类型,允许用户存储不同的数据类型
结构体内存对齐
结构体的大小计算遵循结构体的对齐规则:
结构体对齐规则
1.第一个成员在与结构体变量偏移量为0的地址处。 2.其他成员变量要对齐到对齐数的整数倍的地址处。 3.结构体的总大小为最大对齐数(每个成员变量都有一个对齐数)的整数倍。
对齐数=该结构体成员变量自身的大小与编译器默认的一个对齐数的较小值。
1. 不考虑结构体嵌套的情况
定义两个结构体:
struct A
{
char a;
char b;
int c;
};
struct B
{
char a;
int b;
char c;
};
struct A 内存对齐示意图
struct B 内存对齐示意图(同理)
验证:
#include <iostream>
using namespace std;
struct A
{
char a;
char b;
int c;
};
struct B
{
char a;
int b;
char c;
};
int main()
{
cout << "size of struct A is " << sizeof(A) << endl;
cout << "size of struct B is " << sizeof(B) << endl;
system("pause");
return 0;
}
结果:
总结: 将占内存小的成员放在一起,大的放在一起合理分配,避免内存浪费。
2. 考虑结构体嵌套的情况
struct A
{
char a;
char b;
int c;
};
struct C
{
char a;
struct A b;
char c;
};
struct C 内存对齐示意图