There has been a number of questions regarding the sizeof
of struct
's (not) being equal to the sum of sizeof
's of its elements. Usually this is due to data alignment. This question is not concerned with data alignment, so please suppose that sizes of all types are multiples of the alignment (say 4B).
As explained here, allocating an array will result in some metadata beeing stored about the size of the allocated array. Let's say we had the following code:
const int size = 10;
struct X {
int someInt;
int array[size];
};
struct Y {
int someInt;
T array[size];
};
Since the size
is known at compile-time, the compiler should be smart enough to determine that there is no need to store any metadata in the case of X
. The compiler could be smart enough to follow this reasoning even in the case of Y
(there could be difference between C and C++ here, since in C++ there is the additional requirement of calling destructors for individual instances of T
).
My question is: am I guaranteed that sizeof(X) == (size + 1) * sizeof(int)
or is it compiler-specific? Or more generally, is sizeof(Y) == size * sizeof(T) + sizeof(int)
?
EDIT: To hopefully clarify things a bit: the question is about both C and C++. Also the original motivation for asking this question is this. If I run
X *foo = new X[100];
or it's C equivalent somewhere in code, will it create a continuous block of memory of size 100 * (size + 1) * sizeof(int)
?