C语言 数据结构内存布局问题

struct A
{
char e;
short f;
};

struct B
{
int a;
char b;
struct A c;
char d;

};

sizeof(struct B); 为什么是12?

struct A
{
char e;
int f;
};

struct B
{
int a;
char b;
struct A c;
char d;

};

sizeof(struct B);为什么是20?

求大牛解释解释 在线等。

http://isnowgo.github.io/2015/08/20/Blog2/
我博客里有详解

第一个是有点奇怪
struct B
{
int a;
char b;
struct A c;
char d;
};
1.什么都不去掉是12
2.只去掉char b;也是12
3.只去掉char d;也是12
4.去掉char b和char d,是8

结构体里嵌套结构体,对齐的计算原则应该是将里面的结构体展开来计算

内存结构分布是这样的(按VS/VC默认8字节对齐):
<-4字节宽度->
|a a a a|
|b e f f|
|d 0 0 0|

4字节宽度是根据sizeof(int)(所有属性中size最大)和8字节中取较小的,另外总的size必须是sizeof(int)的整数倍,不够填充0。
建议你可以找下相关知识充分理解一下。

struct A
{
char e;
int f;
};
struct B
{
int a;
char b;
struct A c;
char d;
};
sizeof(struct B);为什么是20?

<-4字节宽度->
|a a a a|
|b e 0 0|
|c c c c|
|d 0 0 0|