代码如下:
int a = 1;
int* ptr = &a;
float* p1 = (float*)ptr // or reinterpret_cast<float*>(ptr);
cout << *p1 << endl;
当我尝试打印浮点指针 p1 指向的值时,得到的答案为:1.4013e-45。 谁能解释一下为什么会发生这种情况?
最佳答案
Can anyone please explain why is this happening?
您通过与所指向对象的类型不兼容的指针访问对象,因此程序的行为是未定义的。
I was looking to get "1" as the output.
要获得 float 1,您可以将 int 静态转换为 float,或者简单地让转换为隐式:
float f = a;
std::cout << f;
关于c++ - 指向浮点指针的 int 指针 -reinterpret_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67375454/