加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

是否保证C中的数组元素将连续存储,没有填充?

发布时间:2020-12-16 10:06:19 所属栏目:百科 来源:网络整理
导读:换句话说:如果我有这样分配的数组,它是否可以保证: void *arr = calloc(nmemb,sizeof(some_type)) 那么elta,eltb,eltc都将指向内存中的相同位置,这将是此数组some_type类型的第二个元素? some_type *elta = ((some_type*)arr)[1];some_type *eltb = ((som
换句话说:如果我有这样分配的数组,它是否可以保证:

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

那么elta,eltb,eltc都将指向内存中的相同位置,这将是此数组some_type类型的第二个元素?

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

我问这个的原因是因为我试图在C中做一个“容器”,如果这不成立,那么我就没有想法如何返回指向除第一个之外的任何其他元素的指针.

解决方法

是的,它是有保证的.如果添加了填充字节,则它们将添加到struct some_type中,但不会添加到两个数组元素之间.

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是……

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

参考标准:C11,6.2.5.20:

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. […]

(突出显示我!).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读