将 int 指针类型转换为 float 指针

Typecasting int pointer to float pointer

我正在尝试执行以下操作

int a[8]={1,2,3,4,5,6,7,8};

printf("%f\n", *(float *)a);
printf("%f\n", *((float *)a+1));
printf("%f\n", *((float *)a+2));
printf("%f\n", *((float *)a+3));
printf("%f\n", *((float *)a+4));
printf("%f\n", *((float *)a+5));
printf("%f\n", *((float *)a+6));
printf("%f\n", *((float *)a+7));

我明白了

0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000

我尝试以这种方式打印元素的原因是,我想将指向数组的 int 指针转换为 float 指针,并将其作为另一个函数的参数传递,该函数只接受 float *

这个好像不太行。有人可以解释为什么这不起作用吗?

int *ptr;
function((float *)ptr);

如果我这样做,该函数不会正确读取指针指向的值.. 只是返回 0.0000.

这是不正确的。 intfloat 不保证具有相同的对齐方式。

记住:转换一个值和转换一个指针是不同的场景。强制转换指针会更改 way 以引用 type 值,这 几乎肯定 会导致在 大多数 个案例中未对齐。

根据 C11 标准文档,章节 §6.3.2.3

A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned68) for the referenced type, the behavior is undefined.

对于您的情况,变通方法可能是

printf("%f\n", (float)*a);  //cast the value, not the pointer

您不能将指向 int 的指针 转换为指向 float 的指针,并期望将您的值转换为相应的浮点数表示。转换单个值有效,但通过更改指针类型进行转换不会改变表示。

如果你需要一个 float 的数组,声明一个 float 的数组,一次投射一个元素:

float b[8];
for (int i = 0 ; i != 8 ; i++) {
    b[i] = a[i];
}
func_expects_float(b, 8);

将 int 指针转换为 float 不会将整数转换为浮点数。转换只是告诉机器使用指针指向的内存位置的内容作为浮点值而不是整数值。但它不会将值从整数表示更改为浮点表示。

你可以试试:

printf( "%f\n", 1.0f * a[0]); 
printf( "%f\n", 1.0f * a[1]); 
.... 

==或==

printf( "%f\n", *(a+0) * 1.0f ); 
printf( "%f\n", *(a+1) * 1.0f ); 
....