取消引用指针转换变量的地址 [英] Dereferencing the address of a pointer-casted variable
问题描述
我发现这段代码在一个更大的项目中被剪掉了,这让我开始思考.
I found this code snipped in a bigger project and it really got me thinking.
float sift_handler(int rs2, int rs4, int rs5);
int result1;
float temp = sift_hander(rs2, rs4, rs5);
result1 = *(int*)&temp;
据我所知,浮点数的地址 temp
被转换为 int 指针,然后取消引用.当我编译这段代码时,我收到一个警告
As I understand the address of the float temp
is casted to an int pointer and then dereferenced. When I compile this code I get a warning
warning: dereferencing type-punned pointer will break strict-aliasing rules
这样做的真正好处是什么?result1 = temp
?使用 round()
是否比仅使用转换更好?
What are the real benefits of this against
result1 = temp
? Also is it better to use round()
, than just casting?
推荐答案
这对 result1 = temp 的真正好处是什么?
What are the real benefits of this against result1 = temp?
它们是完全不同的操作.result1 = temp
将值从浮点数转换为整数.如果 temp
是 1.0f
,那么 result1
将是 1
.如果默认舍入样式(简单地截断)不令人满意,您可以在赋值给整数之前使用 round()
.
They are completely different operations. result1 = temp
converts value from float to integer. If temp
is 1.0f
, then result1
will be 1
. If default rounding style (which is simply truncation) is not satisfactory, you can use round()
before assignment to integer.
*(int*)&temp
另一方面重新解释 float
变量的位并将这些位存储到整数变量.1.0f
可能会产生一些巨大的整数值.这称为类型双关.
*(int*)&temp
on the other hand reinterprets the bits of float
variable and stores those bits to integer variable. 1.0f
will likely result in some huge integer value. This is called type punning.
正如编译器告诉您的那样,对无效类型的指针进行这种取消引用是严格别名违规.进行此类双关语的正确方法是:
As compiler tells you, doing this derefrence with pointer of invalid type is strict aliasing violation. Correct way to do this type punning would be:
memcpy(&result, &temp, sizeof temp);
这篇关于取消引用指针转换变量的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!