...
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 such as the following. It should be recognized that this is specific to a particular type of machine, and should therefore be done only when necessary.:
Code Block |
---|
unsigned int *ptr = 0xcfcfcfcf; |
These conversions are machine dependent, and should only be coded when absolutely necessary.
Non-Compliant Code Example
In this non-compliant code example, the pointer ptr
is converted to an integer value. Both a pointer and an int
are assumed to be 32 bits. The upper 9 high-order nine 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 number = ptr; number = (number & 0x7fffff) | (flag << 23); ptr = number; |
A similar scheme similar to this was used in early versions of Emacs, sacrificing limiting its portability and its preventing the ability to edit files larger than 8MB.
...
Saving a few bits of storage is generally not so important that it is worth writing nonportable 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, and works even when pointers cannot be represented in any integer type.
...
Code Block | ||
---|---|---|
| ||
char *ptr1; char *ptr2; /* ... */ if (((unsigned)ptr1 & 3) == ((unsigned)ptr2 & 3)) { /* ... */ |
Although this comparison is likely to work on many architectures, it is much less portable than it could be.
...