结构的填充和包装 [英] Structure padding and packing

查看:84
本文介绍了结构的填充和包装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

struct mystruct_A
{
   char a;
   int b;
   char c;
} x;

struct mystruct_B
{
   int b;
   char a;
} y;

结构的尺寸是12和8分别

The sizes of the structures are 12 and 8 respectively.

难道这些结构填充或包装?

Are these structures padded or packed?

在不填充或包装发生的?

When does padding or packing take place?

推荐答案

填充 对齐结构成员自然地址边界 - 例如, INT 成员将有偏移,这是 MOD(4)== 0 在32位平台上。填充默认是开启的。它插入下面的差距成为你的第一个结构:

Padding aligns structure members to "natural" address boundaries - say, int members would have offsets, which are mod(4) == 0 on 32-bit platform. Padding is on by default. It inserts the following "gaps" into your first structure:

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;

包装,从做填充另一方面prevents编译器 - 这必须明确要求 - 根据GCC则是 __属性__((__包装__)),所以以下内容:

Packing, on the other hand prevents compiler from doing padding - this has to be explicitly requested - under GCC it's __attribute__((__packed__)), so the following:

struct __attribute__((__packed__)) mystruct_A {
    char a;
    int b;
    char c;
};

将产生在32位架构尺寸 6 的结构。

不过的注意事项 - 未对齐的内存访问是在架构,允许它(如x86和AMD64)慢,明确禁止的严格对齐架构的SPARC像

A note though - unaligned memory access is slower on architectures that allow it (like x86 and amd64), and is explicitly prohibited on strict alignment architectures like SPARC.

这篇关于结构的填充和包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆