Jim said:
#include <iostream>
#include <string>
int main ()
{
// Method 1
int p1 = 1234;
char n1[4];
*(reinterpret_cast<int*>( n1 )) = p1;
[snip]
This one is interesting. Are you sure, n1 satisfies the alignment
requirements for int? (And I wondern what happens if it is not. Will the
reinterpret_cast modify the pointer so that one gets a valid int* to an
overlapping but different memory region, will the assignment fail, or
will we see the proverbial nasal daemons?)
No, there is no problem with alignment in the above code. However there
are plenty of other reasons to find faults with this program: the double
storage is inefficient while the use of reinterpret_cast is inelegant, to
use as charitable a description as possible).
However unsightly this code may be, it will not blow up when run. Because
the four chars of storage for the int were allocated by a single array
object (n1), the storage will be aligned according the most stringent
alignment requirements of any four-byte sized type (including a four-byte
int type).
In fact a C++ program can always be certain that as long as a character
array is equal to (or larger than) the sizeof() a POD type, then the
program will be able to place of an object of that type into that
character array safely.