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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With