uint data1;
ushort data2;
ushort data3;
uchar data4[8];
std::uint8_t buff[16];
std::uint8_t* out = buff;
out = std::copy_n(reinterpret_cast<std::uint8_t*>(&quid.data1), 4, out);
out = std::copy_n(reinterpret_cast<std::uint8_t*>(&quid.data2), 2, out);
out = std::copy_n(reinterpret_cast<std::uint8_t*>(&quid.data3), 2, out);
std::copy_n(quid.data4, 8, out);
Why will the result in out
will be different if I don't use reinterpret_cast
?
The result will be different because &x
has type T *
, where T
is the type of x
, and pointer arithmetic treats + 1
as "advancing the pointer by sizeof(T)
", so that in effect you treat a pointer as a pointer into an array of elements of that type.
If you change the type of the pointer, you're going to treat the memory it's pointing to as an array of elements of a different type -- for example, treating an int
as an array of char
s.