C 数组可以在元素之间包含填充吗? [英] Can C arrays contain padding in between elements?

查看:15
本文介绍了C 数组可以在元素之间包含填充吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说在 C 中,包含在结构中的数组可能在数组元素之间添加了填充.现在很明显,填充量不能在任何一对元素之间变化,或者用简单的指针算法计算数组中的下一个元素是不可能的.

I heard a rumor that, in C, arrays that are contained inside structs may have padding added in between elements of the array. Now obviously, the amount of padding could not vary between any pair of elements or calculating the next element in an array is not possible with simple pointer arithmetic.

这个谣言还说,不包含在结构中的数组保证不包含填充.我知道至少那部分是真的.

This rumor also stated that arrays which are not contained in structures are guaranteed to contain no padding. I know at least that part is true.

所以,在代码中,谣言是:

So, in code, the rumor is:

{
    // Given this:
    struct { int values[20]; } foo;
    int values[20];

    // This may be true:
    sizeof(values) != sizeof(foo.values);
}

我非常确定 sizeof(values) 将始终等于 sizeof(foo.values).但是,我在 C 标准(特别是 C99)中找不到任何明确确认或否认这一点的内容.

I'm pretty certain that sizeof(values) will always equal sizeof(foo.values). However, I have not been able to find anything in the C standard (specifically C99) that explicitly confirms or denies this.

有谁知道这个谣言是否在任何 C 标准中得到解决?

Does anyone know if this rumor is addressed in any C standard?

edit:我知道在数组 foo.values 的末尾和结构 foo 的末尾之间可能存在填充,并且标准规定 foo 的开头和 foo.values 的开头之间没有填充.但是,有没有人引用的引用或引用的标准,其中说foo.values的元素之间没有填充?

edit: I understand that there may be padding between the end of the array foo.values and the end of the struct foo and that the standard states that there will be no padding between the start of foo and the start of foo.values. However, does anyone have a quote from or reference to the standard where it says there is no padding between the elements of foo.values?

推荐答案

不,数组元素之间永远不会有填充.这是特别不允许的.C99 标准将数组类型称为数组类型描述了一组连续分配的非空对象......".相比之下,结构是连续"分配的,而不是连续"分配的.

No, there will never be padding in between elements of an array. That is specifically not allowed. The C99 standard calls array types "An array type describes a contiguously allocated nonempty set of objects...". For contrast, a structure is "sequentially", not "contiguously" allocated.

结构中的数组之前或之后可能有填充;那完全是另一种动物.编译器可能会这样做以帮助对齐结构,但 C 标准对此没有说明.

There might be padding before or after an array within a structure; that is another animal entirely. The compiler might do that to aid alignment of the structure, but the C standard doesn't say anything about that.

这篇关于C 数组可以在元素之间包含填充吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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