是否保证C中的数组元素将连续存储而不填充? [英] Is it guaranteed that array elements in C will be stored consecutively, with no padding?

查看:59
本文介绍了是否保证C中的数组元素将连续存储而不填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

换句话说:是否可以保证如果我以此方式分配了一个数组:

In other words: is it guaranteed that if I have an array allocated this way:

void *arr = calloc(nmemb, sizeof(some_type))

然后eltaeltbeltc都将指向内存中的同一位置,这将是此数组的some_type类型的第二个元素吗?

Then elta, eltb, eltc will all point to the same location in memory, which will be the second element of type some_type of this array?

some_type *elta = &((some_type*)arr)[1];
some_type *eltb = ((some_type*)arr)+1;
some_type *eltc = (char*)arr+sizeof(some_type);

我之所以这样问,是因为我试图在C语言中做一个容器",如果不成立,那我就不知道如何返回一个指向除C之外的任何其他元素的指针了.第一个.

The reason I’m asking this is because I’m trying to do a "container" in C, and if this doesn’t hold then I’m out of ideas how to return a pointer to any other element than the first one.

推荐答案

是的,可以保证. 如果填充字节被添加,它们将被添加在 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. [...]

(由我突出显示!)

这篇关于是否保证C中的数组元素将连续存储而不填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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