structure-packing

structure apdding and packing

alignment requirements

结构体字段对齐后内存访问比较快。

padding

struct中的成员默认是需要按成员类型的大小进行对齐。 例如:

struct S {
int a;
char b;
char padd[3]; // 这里要加 padd
int c;
};
  • a类型是整数,所以它的地址需要按4字节对齐, 就是&(s.a)%4==0
  • b类型是char,所以它的地址需要按1字节对齐
  • c的类型是int,所以它需要按4字节对齐,就是&(s.c)%4==0, 为了满足这个条件需要插入char padd[3]

struct本身则默认需按字节数最大的成员进行对齐 例如:

struct S {
int a;
char b;
char pad1[3]; // 这里要加 pad1, 为了满足成员c 4字节对齐
int c;
char d
char pad2[3]; // 这里要pad2,为了满足整个结构体4字节对齐
};

插入pad2[3],就是为了满足整个结构体按4字节对齐,因为这个结构体字节数最多的就是int类型占4个字节,因此这个结构体需要按4字节对齐。