A T x[size]
array will always fit exactly into size * sizeof(T)
bytes, meaning that char buffer[size*sizeof(T)]
is always precisely enough to store such an array.
The problem in that answer, as I understood it, was that your char
array is not guaranteed to be properly aligned for storing the object of type T
. Only malloc
-ed/new
-ed buffers are guaranteed to be aligned properly to store any standard data type of smaller or equal size (or data type composed of standard data types), but if you just explicitly declare a char
array (as a local object or member subobject), there's no such guarantee.
Alignment means that on some platform it might be strictly (or not so strictly) required to allocate, say, all int
objects on, say, a 4-byte boundary. E.g. you can place an int
object at the address 0x1000
or 0x1004
, but you cannot place an int
object at the address0x1001
. Or, more precisely, you can, but any attempts to access this memory location as an object of type int
will result in a crash.
When you create an arbitrary char
array, the compiler does not know what you are planning to use it for. It can decide to place that array at the address 0x1001
. For the above reason, a naive attempt to create an int
array in such an unaligned buffer will fail.
The alignment requirements on some platform are strict, meaning that any attempts to work with misaligned data will result in run-time failure. On some other platforms they are less strict: the code will work, but the performance will suffer.
The need for the proper alignment sometimes means that when you want to create an int
array in an arbitrary char
array, you might have to shift the beginning of an int
array forward from the beginning of the char
array. For example, if the char
array resides at 0x1001
, you have no choice but to start your constructed-in-place int
array from the address 0x1004
(which is the char
element with the index 3). In order to accommodate the tail portion of the shifted int
array, the char
array would have to be 3 bytes larger than what the size * sizeof(T)
evaluates to. This is why the original size might not be enough.
Generally, if your char
array is not aligned in any way, you will really need an array of size * sizeof(T) + A - 1
bytes to accommodate an aligned (i.e. possibly shifted) array of objects of type T
that must be aligned at A-byte boundary.