8

I have a pointer. On a 32-bit system it's 32 bits. On a 64-bit system it's 64 bits.

I have a long long integer field used as an identifier, and sometimes I want to use the pointer value in there. (I never cast back to a pointer - once I've cast it to the integer field, I only ever compare it for equality).

On both 32-bit and 64-bit systems, it seems safe to do this. (On larger pointered systems not so). Is that true?

And then, is there a way to make GCC not give the following warning only when building on platforms where this is safe (which is, at the moment, all target platforms)?

error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]

4

2 回答 2

10

根据标准,不能保证指针适合整数类型。实际上,否则,在大多数个人计算机上,存在几种内存模型。您可以看到指针和整数类型的大小并不总是相同(即使在“传统”计算机上也是如此)。

您应该使用 C99 中的可选类型intptr_tand uintptr_t

C11 (n1570),第 7.20.1.4 节

以下类型指定了一个有符号整数类型,其属性是任何有效的指针void都可以转换为此类型,然后转换回指向 的指针void,结果将与原始指针进行比较:intptr_t

以下类型指定了一个无符号整数类型,该类型的任何有效指针void都可以转换为该类型,然后转换回指向 的指针void,结果将与原始指针进行比较:uintptr_t

这是一个小例子:

#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

如果您想要一个保证足够大以容纳指针的整数类型,请考虑intptr_t(signed) 或uintptr_t. 该标准保证这些数据类型大到足以容纳一个指针。没有什么可以假设的,尤其long int是时间不够长。

于 2012-11-08T11:24:14.027 回答