Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 909
BeeOnRope Avatar asked Sep 27 '17 22:09

BeeOnRope


2 Answers

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.

like image 151
melpomene Avatar answered Nov 12 '22 08:11

melpomene


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

like image 45
Lily Ballard Avatar answered Nov 12 '22 08:11

Lily Ballard