...
In this noncompliant code example, the pointer ptr
is converted to an integer value. Both a pointer and an int
are assumed to be 32 bits. The high-order 9 bits of the number are used to hold a flag value, and the result is converted back into a pointer.
Code Block | ||||
---|---|---|---|---|
| ||||
char *ptr; unsigned int flag; /* ... */ unsigned int number = (unsigned int)ptr; number = (number & 0x7fffff) | (flag << 23); ptr = (char *)number; |
...
Saving a few bits of storage is generally not as important as writing portable code. A struct
can be used to provide room for both the pointer and the flag value. This is portable to machines of different word sizes, both smaller and larger than 32 bits, working even when pointers cannot be represented in any integer type.
Code Block | ||||
---|---|---|---|---|
| ||||
struct ptrflag { char *pointer; unsigned int flag :9; } ptrflag; char *ptr; unsigned int flag; /* ... */ ptrflag.pointer = ptr; ptrflag.flag = flag; |
...
It is sometimes necessary in low level kernel or graphics code to access memory at a specific location, requiring a literal integer to pointer conversion. In this non-compliant code, a pointer is set directly to an integer constant, where it is unknown whether the result will be as intended.
Code Block | ||||
---|---|---|---|---|
| ||||
unsigned int *ptr = 0xcfcfcfcf; |
...
Adding an explicit cast may help the compiler convert the integer value into a valid pointer.
Code Block | ||||
---|---|---|---|---|
| ||||
unsigned int *ptr = (unsigned int *) 0xcfcfcfcf; |
...