一.一般类型
约定为32位系统,即char 1字节、short 2字节、int 4字节,指针是地址4个字节
定义:偏移量
偏移量指的是结构体变量中成员的地址和结构体变量地址的差。结构体大小等于最后一个成员的偏移量加上最后一个成员的大小
struct note
{
int a;----0偏移量
char b;----4+0偏移量
short c;----1+4偏移量,但要是short的整数倍,所以得补1位
}note1;
sizeof(note1) = 2(short长度) + 6(偏移量) = 8;
二.内嵌结构体
struct note
{
char a;----0偏移量
struct date
{
short c;----1+0偏移量,但要是int d整数倍,所以得补3,偏移量就是4
int d;----2+4偏移量,不是int的整数倍,得补2,偏移量就是8
}date1;
short e;----4+8偏移量,不用补,是short的整数倍
}note1;
sizeof(note1) = 2+12=14,由于14不是int的整数倍,得补2,所以是16
三.如果指定了对齐值
#pragma pack(1)
struct A
{
char a; //0
int b;//1+0
short c;4+1
};
sizeof(A) = 2+4+1=7
#pragma pack(1)
struct B
{
char a;//0
short b;//1+0
int c;//2+1
};
sizeof(B) = 4+2+1=7
四.结构体有指针
struct C
{
char a;----0偏移量
char *b;----1+0偏移量
int c;----4+1偏移量,由于不是int整数倍,得补3,偏移值就是8
short d;----4+8
int *e;----2+12=14不是int整数倍,得补2,偏移量就是16
}
sizeof(C) = 4+16=20