May 3, 2018 at 9:28am UTC
I have a char array
char * array
which contains 3 float variables (in binary) and I want to extract it into a struct:
1 2 3 4 5 6
struct float3
{
float data1;
float data2;
float data3;
}
First time I tried to use
float3& floats = reinterpret_cast <float3&>(array)
but I got incorrect values.
Then I used:
1 2
float3 floats;
memcpy(&floats, array, 12);
This is worked well.
Can you help me guys what is the explanation of this ?
Last edited on May 3, 2018 at 9:34am UTC
May 3, 2018 at 9:57am UTC
float3& floats = *reinterpret_cast <float3* >(array)
Explanation
I have a char array char * array
which contains 3 float variables (in binary) ...
That is, a pointer to a
struct float3
, so you must describe is as such.
reinterpret_cast <float3*>(array)
You then want to assign it to a reference, so you need to derefernce the pointer.
float3& floats = * reinterpret_cast <float3*>(array);
Last edited on May 3, 2018 at 10:04am UTC
May 3, 2018 at 1:28pm UTC
memcpy and structs may be risky. c++ compilers (it depends) have an 'alignment' setting that can make this not work right. Just an awareness thing, it works here but may not on other code.
May 3, 2018 at 3:09pm UTC
Sorry, I added wrong topic name, the correct is: why memcpy() works while reinterpret_cast not
Thank you kbw ! I had some misunderstanding of references.
Last edited on May 3, 2018 at 4:27pm UTC