简体   繁体   中英

int pointer to float pointer - reinterpret_cast

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?

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;

Integer values used in float or double representations are denormal and are converted according to the IEEE 754 standard .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM