why reinterpret_cast works while memcpy() not

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
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
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.
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
Topic archived. No new replies allowed.