Technically, no. You are at risk of falling foul of your CPU's alignment rules, if it has any.
You may alias an object byte-by-byte using char*
, but you can't take an actual char
array (no matter where its values came from) and pretend it's some other object.
You will see that reinterpret_cast<int*>
method a lot, and on many systems it will appear to work. However, the "proper" method (if you really need to do this at all) is:
const auto INT_SIZE = sizeof(int);
char ch[INT_SIZE] = {};
// Convert to char array
const int x = 100;
std::copy(
reinterpret_cast<const char*>(&x),
reinterpret_cast<const char*>(&x) + INT_SIZE,
&ch[0]
);
// Convert back again
int y = 0;
std::copy(
&ch[0],
&ch[0] + INT_SIZE,
reinterpret_cast<char*>(&y)
);
Notice that I only ever pretend an int
is a bunch of char
s, never the other way around.
Notice also that I have also swapped your memcpy
for type-safe std::copy
(although since we're nuking the types anyway, that's sort of by-the-by).