且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否保证C中的数组元素将连续存储而不填充?

更新时间:2023-11-11 23:44:52

是的,可以保证. 如果填充字节被添加,它们将被添加在 struct some_type之内,但不在两个数组元素之间.

Yes, it is guaranteed. If padding bytes are added, they are added within struct some_type, but not in between two array elements.

E. g.:

struct S
{
    int n;
    short s;

// this is just for illustration WHERE byte padding (typically) would occur!!!
#if BYTE_ALIGNMENT >= 4
    unsigned char : 0;
    unsigned char : 0;
#endif
};
struct S s[2];
size_t d = (char*)(s + 1) - (char*)s;

在将字节对齐方式调整为4或8(甚至更大的2的幂)的情况下,此结构的大小将为8,而d将相等地为8,在将字节对齐方式设置为1或2时,该结构的大小将为6就像会...

With byte alignment adjusted to 4 or 8 (or even larger powers of 2), this struct will have size of 8 and d will be equally 8, with byte alignment set to 1 or 2, the struct will have size of 6 just as will be d...

注意:这不是唯一可能出现填充字节的地方:如果切换成员ns,则在sn之间需要填充字节才能正确对齐n .另一方面,n以后不再需要填充字节,因为结构大小已经可以确保正确对齐.

Note: This is not the only place where padding bytes can occur: If you switched members n and s, padding bytes would be needed in between s and n to get n correctly aligned. On the other hand, no padding bytes would be necessary after n any more as the structure size would assure correct alignment already.

参考标准:C11,6.2.5.20:

Referring to the standard: C11, 6.2.5.20:

数组类型描述了具有特定成员对象类型(称为元素类型)的连续分配的非空对象集. 36)数组类型的特征在于其元素类型和数组中元素的数量. [...]

An array type describes a contiguously allocated nonempty set of objects with a particular member object type, called the element type. 36) Array types are characterized by their element type and by the number of elements in the array. [...]

(由我突出显示!)