铸造int值指针 - 为什么转换为长的第一? (如在发p =(无效*)42) [英] Cast int to pointer - why cast to long first? (as in p = (void*) 42; )
问题描述
在 GLib的文档,对类型转换宏一章。
在转换的讨论的 INT
到 *无效
指针它说(重点煤矿):
天真,你可以试试这个,但它是不正确的:
gpointer磷;
INT I;
P =(无效*)42;
I =(INT)P;
同样,这例子是不正确的,不要复制它。 的问题是
,在一些你需要做这样的系统:gpointer磷;
INT I;
P =(无效*)(长)42;
I =(INT)(长)P;
块引用>(来源:GLib的参考手册GLib的2.39.92,章类型转换宏)。
这是为什么投地
长
有必要吗?如若任何需要加宽
INT
不如转换为指针的一部分自动发生?解决方案作为根据
C99:6.3.2.3
报价:
5的整数可以被转换为任何指针类型。除
previously规定,其结果是实现定义的,可能不
正确对齐,可能不会指向引用的实体
类型,并且可能是一个陷阱重新presentation.56)
6不限指针类型可被转换成一个整数类型。除
previously指定,其结果是实现定义。如果
结果不能重新在整型psented $ P $,该行为是
未定义。结果不必是任何值的范围
整数类型。
块引用>据当时链接您的文档提到:
指针总是面积至少为32位(在所有平台上GLib的
打算支持)。因此,你可以存储至少32位整数值
在指针值。
块引用>和进一步<一个href=\"http://stackoverflow.com/questions/4329777/is-long-guaranteed-to-be-at-least-32-bits\"><$c$c>long$c$c>被保证是ATLEAST 32位的。
因此,code
gpointer磷;
INT I;
P =(无效*)(长)42;
I =(INT)(长)P;时更安全,更便携,仅用于高达32位整数明确,由耍贫嘴的广告。
In the GLib documentation, there is a chapter on type conversion macros. In the discussion on converting an
int
to a*void
pointer it says (emphasis mine):Naively, you might try this, but it's incorrect:
gpointer p; int i; p = (void*) 42; i = (int) p;
Again, that example was not correct, don't copy it. The problem is that on some systems you need to do this:
gpointer p; int i; p = (void*) (long) 42; i = (int) (long) p;
(source: GLib Reference Manual for GLib 2.39.92, chapter Type Conversion Macros ).
Why is that cast to
long
necessary?Should any required widening of the
int
not happen automatically as part of the cast to a pointer?解决方案As according to the
C99: 6.3.2.3
quote:5 An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.56)
6 Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.
According to the documentation at the link you mentioned:
Pointers are always at least 32 bits in size (on all platforms GLib intends to support). Thus you can store at least 32-bit integer values in a pointer value.
And further more
long
is guaranteed to be atleast 32-bits.So,the code
gpointer p; int i; p = (void*) (long) 42; i = (int) (long) p;
is safer,more portable and well defined for upto 32-bit integers only, as advertised by GLib.
这篇关于铸造int值指针 - 为什么转换为长的第一? (如在发p =(无效*)42)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!