下面是我为了解类型转换而编写的一些代码,但我不明白为什么浮点数或双精度值的值打印为"0.000000",即使我从整数数组中输入或尝试从联合的地址解释.
#include <stdio.h>
union test1
{
int x;
float y;
double z;
};
int main()
{
int x[2]={200,300};
float *f;
f=(float*)(x);
printf("%f\n",*f); /*(1)why is this value 0.0*/
*f=(float)(x[0]); /*(2)this works as expected and prints 200.00000*/
printf("%f\n",*f);
union test1 u;
u.x=200;
/*(3)this line give compilation error why*/
//printf ("sizeof(test1) = %d \n", sizeof(test1));
/*(4) this line also prints the value of float and double as 0.0000 why*/
printf ("sizeof(test1) = %lu u.x:%d u.y:%f u.z:%lf \n", sizeof(u), u.x, u.y, u.z);
return 0;
Run Code Online (Sandbox Code Playgroud)
}
首先,int
和float
不兼容的类型.
在你的代码中,通过说
f=(float*)(x);
Run Code Online (Sandbox Code Playgroud)
换句话说,你不能只是指向一个指针float
,将其转换为int *
取消引用int *
以获取int
值.引用维基百科的文章,
函数中的[...]指针参数如果指向根本不同的类型,则假定它们不是别名,[...]
有关详细说明,请参阅已链接的常见问题解答答案.