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
&xhas typeT *, whereTis the type ofx, and pointer arithmetic treats+ 1as “advancing the pointer bysizeof(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
intas an array ofchars.