c++ - 指向浮点指针的 int 指针 -reinterpret_cast

标签 c++ casting reinterpret-cast

代码如下:

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/

相关文章:

c++ - 我是否需要在多线程环境中保护对 STL 容器的读取访问?

c++ - fprintf 与 std::ofstream 的非常令人惊讶的性能(fprintf 非常慢)

c++ - 用http get下载一张图片,只下载了一小部分

python - 从另一个 DataFrame 初始化一个新的 DataFrame 时 dtypes 改变了

java - 反序列化时如何找到对象所属的正确子类?

c++ - 使用 reinterpret_cast 转换指针的段错误

c++ - 为什么 priority_queue 没有 front() 而有 top()

c++ - 使用 reinterpret_cast 将文件读入结构

c++ - 通过引用传递参数时的C++类型转换

在 c 中转换 volatile 变量