请考虑:
struct mystruct_A
{
char a;
int b;
char c;
} x;
struct mystruct_B
{
int b;
char a;
} y;
struct 尺寸分别为12和8.
这些 struct 是填充的还是打包的?
什么时候进行填充或包装?
请考虑:
struct mystruct_A
{
char a;
int b;
char c;
} x;
struct mystruct_B
{
int b;
char a;
} y;
struct 尺寸分别为12和8.
这些 struct 是填充的还是打包的?
什么时候进行填充或包装?
Padding aligns个 struct 成员"自然"寻址边界——例如,int
个成员将具有偏移量,在32位平台上为mod(4) == 0
.默认情况下,"填充"处于启用状态.它会在第一个 struct 中插入以下"间隙":
struct mystruct_A {
char a;
char gap_0[3]; /* inserted by compiler: for alignment of b */
int b;
char c;
char gap_1[3]; /* -"-: for alignment of the whole struct in an array */
} x;
Packing,另一方面防止编译器进行填充-这必须明确要求-在GCC下为__attribute__((__packed__))
,因此如下所示:
struct __attribute__((__packed__)) mystruct_A {
char a;
int b;
char c;
};
将在32位体系 struct 上产生大小为6
的 struct .
不过需要注意的是,在允许未对齐内存访问的体系 struct (如x86和amd64)上,未对齐内存访问速度较慢,在SPARC等strict alignment architectures上,未对齐内存访问被明确禁止.