1—————————————–
struct
{
char b;
int a;
short c;
}A;
sizeof(A) = 12;
b: 1*0 = 0
a: 4*1 = 4
c: 2*4 = 8
2-----
struct A
{
int a;
double b;
float c;
};
struct
{
char e[2];
int f;
double g;
short h;
struct A i;
}B;
//对齐单位 8 个字节
sizeof(B) = 48;
//普通成员偏移量
e: 2*0 = 0
f: 4*1 = 4
g: 8*1 = 8
h: 2*8 = 16
结构体起点坐标:
8*3 = 24
//结构体成员偏移量
a: 24 + 4*0 = 24
b: 24 + 8*1 = 32
c: 24 + 4*4 = 40
3------------------------
struct A
{
char e;
short f;
};
struct
{
int a;
char b;
struct A c;
char d;
}B;
sizeof(B) = 12;
a: 4*0 = 0;
b: 1*4 = 4;
结构体起点坐标:
2*3 = 6
e: 6+1*0 = 6
f: 6+2*1 = 8
d: 1*10 = 10
4-----------------
struct A
{
int e;
short f;
};
struct
{
int a;
char b;
struct A c;
short d;
}B;
sizeof(B) = 20;
a: 4*0 = 0
b: 1*4 = 4
结构体起点:
4*2 = 8
e: 8 + 4*0 = 8
f: 8 + 2*2 = 12 //结构体A所占的大小为该结构体成员内部最大元素的整数倍,不足补齐。
d: 2*8 = 16
5-----------------
#pragma pack(2) //指定对齐单位为2个字节
typedef struct
{
int a;
char b;
short c;
char d;
}A;
a:2*0 = 0
b: 1*4 = 4
c: 2*3 = 6
d: 1*8 = 8
sizeof(A) = 10;
6——————
#pragma pack(2)
typedef struct
{
char a;
char b;
short c;
int d;
}A;
a: 1*0 = 0
b: 1*1 = 1
c: 2*1 = 2
d: 2*2 = 4
sizeof(A) = 8;