9.6.4 Special Pointer Targets

Pointers and integers are not interchangeable. Assigning an integer value to a pointer will generate a warning to this effect. For example:

const char * cp = 0x123; // the compiler will flag this as bad code

There is no information in the integer, 0x123, relating to the type, size or memory location of the destination. Avoid assigning an integer (whether it be a constant or variable) to a pointer at all times. Addresses assigned to pointers should be derived from the address operator "&" that C provides.

In instances where you need to have a pointer reference a seemingly arbitrary address or address range, consider defining an object or label at the desired location. If the object is defined in assembly code, use a C declaration (using the extern keyword) to create a C object which links in with the external object and whose address can be taken.

Take care when comparing (subtracting) pointers. For example:

if(cp1 == cp2)

; take appropriate action

The ANSI C standard only allows pointer comparisons when the two pointer targets are the same object. The address may extend to one element past the end of an array.

Comparisons of pointers to integer constants are even more risky, for example:

if(cp1 == 0x246)

; take appropriate action

A NULL pointer is the one instance where a constant value can be safely assigned to a pointer. A NULL pointer is numerically equal to 0 (zero), but since they do not guarantee to point to any valid object and should not be dereferenced, this is a special case imposed by the ANSI C standard. Comparisons with the macro NULL are also allowed.