简体   繁体   中英

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM