Pointer to a larger number int

I have a pointer. On a 32-bit system, this is 32 bits. On a 64-bit system, this is 64 bits.

I have a long integer field used as an identifier, and sometimes I want to use a pointer value here. (I never go back to a pointer - as soon as I pass it to an integer field, I only ever compare it for equality).

For both 32-bit and 64-bit systems, this is safe. (In larger switch systems, not so). It's true?

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

error: casting to a pointer from an integer of different sizes [-Werror = int-to-pointer-cast]

+7
source share
2 answers

In accordance with the standard, there is no guarantee that the pointer matches an integer type. In practice, otherwise, on most personal computers there are several memory models . You can see that pointers and integer types do not always have the same size (even on "regular" computers).

You are better off using the optional intptr_t and uintptr_t types starting with C99.

C11 (n1570), ยง 7.20.1.4

The following type denotes an integer type that is familiar with the property that any valid pointer to void can be converted to this type and then converted back to a pointer to void , and the result will be compared with the original pointer: intptr_t .

The following type denotes an unsigned integer type with the property that any valid pointer to void can be converted to this type and then converted back to a pointer to void , and the result is comparable 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); 
+9
source

If you want the integer type to be large enough to hold the pointer, consider intptr_t (signed) or uintptr_t . The standard ensures that these data types are large enough to hold the pointer. Nothing else can be accepted, especially not that long int is long enough.

+1
source

All Articles