c - 指针类型转换为不同的数据类型

标签 c pointers casting

在 g 的情况下,(float*) 特别做什么。如果我写g = *&i;那么输出是正常的,即g=f,但是如果g = *(float*)&i;那么为什么g=0.0000? ??

#include <stdio.h>

int main()
{

int i = 37;
int *p;
p = &i;
float f = i;
printf("%d\n", i);
printf("%d\n", p);
printf("%d\n", *p);
float g = *(float*) &i;
printf("i = %d   f = %f   g = %f", i, f, g);
}

最佳答案

g = *&ig = i 相同,是将 int 赋值给 float。编译器通过=运算符执行转换:

  1. 加载整数,2.转换为浮点格式,3.存储为 float 。除了舍入问题之外,效果很好。

另一种构造是将整数指针重新解释为浮点指针。由于 float ( float 通常使用一些位表示尾数,一些位表示指数)和整数(整数只是按 8 位逐 8 位序列化到内存)的数据格式不同,编译器只是将数据从源复制到没有任何额外转化的目的地,您就得不到您想要的东西。

关于c - 指针类型转换为不同的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40139591/

相关文章:

c - 如何将 CRC 函数从 C 转换为 Ruby?

c - 警告 : control reaches end of non-void function [-Wreturn-type] }

c - 将字符分配给整数并进行比较

C 中用于不返回任何内容的函数的 Python 模块

c - printf 和转换 float 参数

c - 你如何在 C 中将结构成员排序到队列中?

c - C 中的指针和字符串

c - 替换(不修改) 'const' 值,合法吗?

python - 在 numpy 中强制非数字字符为 NA(将 csv 读取到 pandas 数据帧时)

java - 这是编译或反编译的副作用吗?