Is it guaranteed that sizeof(T[N]) == N * sizeof(T)?

本秂侑毒 提交于 2020-01-13 08:57:07

问题


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?

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]).


回答1:


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

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.




回答2:


The whole point of sizeof is it includes the relevant padding. Every element of an array is exactly sizeof(T) bytes after the previous element. So the size of the entire array is N * sizeof(T).



来源:https://stackoverflow.com/questions/46458363/is-it-guaranteed-that-sizeoftn-n-sizeoft

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!