废话不多说,直接通过来看一下C语言结构体的内存分配。
1:
typedef struct _a {
char c1;
long I;
char c2;
double f;
} a;
typedef struct _b {
char c1;
char c2;
long I;
double f;
} b;
typedef struct _c {
char c1;
long I;
a a1;
char c2;
} c;
printf("%lu\n", sizeof(a));
printf("%lu\n", sizeof(b));
printf("%lu\n", sizeof(c));
打印结果如下:
32
24
56
下面通过画图的方式来讲解上面的打印结果。
2:
#pragma pack(push)
#pragma pack(4)
typedef struct _a {
char c1;
long I;
char c2;
double f;
} a;
typedef struct _b {
char c1;
char c2;
long I;
double f;
} b;
typedef struct _c {
char c1;
long I;
a a1;
char c2;
} c;
#pragma pack(pop)
printf("%lu\n", sizeof(a));
printf("%lu\n", sizeof(b));
printf("%lu\n", sizeof(c));
打印结果如下:
24
20
40
#pragma pack(4)
指定内存对齐的字节数,该以4个字节进行对齐,所以内存图如下: