结构填充如何工作? [英] How structure padding works?

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

问题描述

我的问题与结构填充有关?谁能告诉我结构填充背后的逻辑是什么.

My Questing is regarding structure padding? Can any one tell me what's logic behind structure padding.

示例:

结构节点{ char c1; short s1; char c2; int i1; };

structure Node{ char c1; short s1; char c2; int i1; };

任何人都可以告诉我如何将结构填充应用于此结构吗?

Can any one tell me how structure padding will apply on this structure?

假设:整数需要4个字节.

Assumption: Integer takes 4 Byte.

等待答案.

推荐答案

填充的工作方式完全取决于实现.

How padding works depends entirely on the implementation.

对于具有两个字节的short和四个字节的int且类型必须与其大小倍数对齐的实现,您将具有:

For implementations where you have a two-byte short and four-byte int and types have to be aligned to a multiple of their size, you will have:

Offset  Var   Size
------  ----  ----
   0     c1      1
   1     ??      1
   2     s1      2
   4     c2      1
   5     ??      3
   8     i1      4
  12    next

无论出于何种原因,实现都可以自由地在结构的字段之间插入填充,并在最后一个字段之后(但在第一个字段之前 not )插入填充.在结构后填充的能力对于对齐阵列中的后续元素很重要.例如:

An implementation is free to insert padding between fields of a structure and following the last field (but not before the first field) for any reason whatsoever. The ability to pad after a structure is important for aligning subsequent elements in an array. For example:

struct { int i1; char c1; };

可能会给您:

Offset  Var   Size
------  ----  ----
   0     i1      4
   4     c1      1
   5     ??      3
   8    next

填充通常是因为对齐数据工作更快,或者对齐数据是非法的(某些CPU体系结构不允许对齐访问).

Padding is usually done because either aligned data works faster, or misaligned data is illegal (some CPU architectures disallow misaligned access).

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

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