是否可以保证sizeof(T [N])== N * sizeof(T)? [英] Is it guaranteed that sizeof(T[N]) == N * sizeof(T)?

查看:113
本文介绍了是否可以保证sizeof(T [N])== N * sizeof(T)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为,由sizeof返回的N个类型为T的元素的数组的大小可以保证恰好是sizeof(T)的N倍.

I had always assumed that the size of an array of N elements of type T, as returned by sizeof was guaranteed to be exactly N times sizeof(T).

The comments on this question made me doubt it though. There are claims from reputable users that arrays may contain padding, which would break the equality. Of course such platforms may not exist, but are they allowed?

如果允许的话,这会破坏许多常见的习惯用法,例如使用N * sizeof(T)计算数组所需的存储空间,或使用sizeof(a)/sizeof(a[0])计算数组中元素的数量.

If allowed, this would break many common idioms, such as calculating the needed storage for an array with N * sizeof(T), or calculating the number of elements in an array using sizeof(a)/sizeof(a[0]).

推荐答案

是. [expr.sizeof] 包括有关sizeof的这一点:

Yes. [expr.sizeof] includes this bit about sizeof:

应用于数组时,结果是数组中的字节总数.这意味着 n 个元素的数组的大小是元素的大小的 n 倍.

When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of n elements is n times the size of an element.

这篇关于是否可以保证sizeof(T [N])== N * sizeof(T)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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