代码
#include <iostream>
using namespace std;
struct example1
{
short a;
long b;
};
struct example2{
char c;
example1 struct1;
short e;
};
struct example3{
char c;
example1 struct1;
long long e;
};
struct example4{
char c;
int a;
char e;
};
#pragma pack(2)
void test()
{
cout << "long long = "<<sizeof(long long) <<endl;
cout << "sizeof(struct example1) ="<< sizeof(struct example1) <<endl;
cout << "sizeof(struct example2) ="<< sizeof(struct example2) <<endl;
cout << "sizeof(struct example3) ="<< sizeof(struct example3) <<endl;
cout << "sizeof(struct example4) ="<< sizeof(struct example4) <<endl;
example3 struct3;
cout << "&struct3.c ="<<(unsigned int)(&struct3.c) - (unsigned int)(&struct3) << endl;
cout << "&struct3.struct1 ="<<(unsigned int)(&struct3.struct1) - (unsigned int)(&struct3) << endl;
cout << "&struct3.e ="<<(unsigned int)(&struct3.e) - (unsigned int)(&struct3) << endl;
example4 struct4;
cout << "&struct4.c ="<<(unsigned int)(&struct4.c) - (unsigned int)(&struct4) << endl;
cout << "&struct4.a ="<< (unsigned int)(&struct4.a) - (unsigned int)(&struct4) << endl;
cout << "&struct4.e ="<< (unsigned int)(&struct4.e) - (unsigned int)(&struct4) << endl;
}
int main(int argc, char *argv[])
{
test();
return 0;
}
结果
计算
example1
struct example1
{
short a;
long b;
};
short 是2字节,long 是4字节。
b是4字节大小,只能在4的倍数地址开始存放。
a从0地址放入2字节数据;
地址到了2,而b是4字节,需要从4倍数地址开始存放,于是补全2字节空间,在4地址放入b数据。
0表示空闲内存,1表示使用1字节内存
结构内存分布:
变量 a b
内存分布 1,1,0,0,1,1,1,1
于是 sizeof(struct example1) = 8
example2
struct example2{
char c;
example1 struct1;
short e;
};
char 是1字节,short 是2字节。example1 中最大成员long大小是4字节,需要从4倍数地址开始存放。
c从0地址放入1字节数据;
地址到了1,而struct1是4字节对齐,需要从4倍数地址开始存放,于是补齐3字节空间,在4地址放入8字节的struct1数据;
地址到了12,放入e,而e是2字节,在最后需要按4字节对齐,补全2个字节。
0表示空闲内存,1表示使用1字节内存
结构内存分布:
变量 c struct1 e
内存分布 1,0,0,0,1,1,0,0,1,1,1,1,1,1,0,0
于是 sizeof(struct example2) = 16
example3
struct example3{
char c;
example1 struct1;
long long e;
};
char 是1字节,long long 是8字节。example1 中最大成员long大小是4字节,需要从4倍数地址开始存放, e需要从8倍地址开始存放。
c从0地址放入1字节数据;
地址到了1,而struct1是4字节对齐,需要从4倍数地址开始存放,于是补齐3字节空间,在4地址放入8字节的struct1数据;
地址到了12,不是e的8倍地址,于是补全4字节空间,在16地址放入e,而e是8字节大小,是example3中最大的,以8字节对齐,故末尾不需要补齐空间。
0表示空闲内存,1表示使用1字节内存
结构内存分布:
变量 c struct1 e
内存分布 1,0,0,0,1,1,0,0,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1
于是 sizeof(struct example3) = 24
example4
struct example4{
char c;
int a;
char e;
};
char 是1字节,int 是4字节。a需要从4倍数地址开始存放。
c从0地址放入1字节数据,此时地址到了1,而a是4字节对齐,需要从4倍数地址开始存放,于是补齐3字节空间,在4地址放入4字节的a,之后在8地址放入e,而e是1字节大小,z在末尾需要补齐3字节空间。
0表示空闲内存,1表示使用1字节内存
结构内存分布:
变量 c a e
内存分布 1,0,0,0,1,1,1,1,1,0,0,0
于是 sizeof(struct example4) = 12