int pointer to float pointer - reinterpret_cast

Viewed 285

Following is the code:

int a = 1;
int* ptr = &a;
float* p1 = (float*)ptr // or reinterpret_cast<float*>(ptr);
cout << *p1 << endl;

When I try to print the value pointed by float pointer p1, I get the answer as: 1.4013e-45. Can anyone please explain why is this happening?

2 Answers

Can anyone please explain why is this happening?

You access an object through a pointer that is incompatible with the type of the pointed object, and therefore the behaviour of the program is undefined.

I was looking to get "1" as the output.

To get a float 1, you can static_cast int to float, or simply let the conversion be implicit:

float f = a;
std::cout << f;
Related