8

ポインタがあります。32ビットシステムでは、32ビットです。64ビットシステムでは、64ビットです。

識別子としてlonglong整数フィールドを使用していますが、そこでポインター値を使用したい場合があります。(ポインターにキャストバックすることはありません。整数フィールドにキャストすると、等しいかどうかを比較するだけです)。

32ビットシステムと64ビットシステムの両方で、これを行うのは安全のようです。(より大きなポインターシステムではそうではありません)。本当?

そして、これが安全なプラットフォーム(現時点ではすべてのターゲットプラットフォーム)でビルドする場合にのみ、GCCが次の警告を出さないようにする方法はありますか?

エラー:異なるサイズの整数からポインターにキャスト[-Werror =int-to-pointer-cast]

4

2 に答える 2

10

According to the standard, there is no guarantee that a pointer fits in an integer type. In practical, otherwise, on mostly personnal computers, there exists several memory models. You can see pointer and integer types have not always the same size (even on "conventional" computers).

You should rather use the optional types intptr_t and uintptr_t, from C99.

C11 (n1570), § 7.20.1.4

The following type designates a signed integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer: intptr_t.

The following type designates an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer: uintptr_t.

Here is a small example:

#include <stdio.h>
#include <stdint.h>

int n = 42;
int *p = &n;
intptr_t i = (intptr_t)(void *)p;
int *q = (void *)i; 

printf("%d\n", *q);
于 2012-11-08T11:23:54.170 に答える
1

If you want to have an integer type that is guaranteed to be big enough to hold a pointer, consider intptr_t (signed) or uintptr_t. The standard guarantees that these datatypes are big enough to hold a pointer. Nothing else might be assumed, especially not that long int is long enough.

于 2012-11-08T11:24:14.027 に答える