类型为int的指针指向浮点指针 [英] Typecasting int pointer to float pointer
问题描述
int a [8] = {1,2,3,4, 5,6,7,8};
printf(%f\\\
,*(float *)a);
printf(%f\\\
,*((float *)a + 1));
printf(%f\\\
,*((float *)a + 2));
printf(%f\\\
,*((float *)a + 3));
printf(%f \ n,*((float *)a + 4));
printf(%f\\\
,*((float *)a + 5));
printf(%f\\\
,*((float *)a + 6));
printf(%f\\\
,*((float *)a + 7));
我得到
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
$ c $我试图以这种方式打印元素的原因是因为,我想将int指针转换为数组到float指针并将其作为另一个只需要 float *
的函数的参数传递。
看起来这样做效果不好。有人可以解释为什么这是行不通的?
int * ptr;
函数((float *)ptr);
如果我这样做,函数不读取指针正确指向的值。 0.0000
。
解决方案这是不正确的。 int
和 float
不保证具有相同的对齐方式。
记住:投射值和投射指针是不同的情况。投射指针会改变方式来引用类型值,几乎肯定会导致中的大部分 / b>
根据 C11
标准文档,第6.3.2.3节
指向对象类型的指针可能被转换为指向不同对象类型的指针。如果生成的指针没有正确对齐引用类型,那么行为是不确定的。
在你的情况下,一个解决方法可能是
printf(%f \ n ,(float)* a); //转换值,而不是指针
I'm trying to do the following
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));
I get
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
The reason why I'm trying to print the elements in this way is because, I want to cast the int pointer to the array to the float pointer and pass it as a parameter for another function which only takes float *
.
It seems that this does not work well. Can someone explain why this is not working?
int *ptr;
function((float *)ptr);
If I do this the function does not read the values the pointer is pointing to properly.. just returning 0.0000
.
解决方案 This is not correct. int
and float
are not guaranteed to have the same alignment.
Remember: Casting a value and casting a pointer are different scenarios. Casting a pointer changes the way to refer to the type value, which can almost certainly result in a mis-alignment in most of the cases.
As per C11
standard document, chapter §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.
In your case, a work-around may be
printf("%f\n", (float)*a); //cast the value, not the pointer
这篇关于类型为int的指针指向浮点指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!