While it used to be common practice to use integers and pointers interchangeably in C (although it was not considered good style), the C99 standard has mandated that pointer to integer and integer to pointer conversions are implementation defined. This means that they are not necessarily portable from one system to the next, and additionally multiple conversions may or may not give the desired behavior.
Universal Integer/Pointer Storage
It is recommended to use a union if you need to memory to be accessible as both a pointer and an integer rather than make the cast. Since a union is the size of the largest element and will faithfully represent both as the implementation defines, it will ensure the proper behavior and keep data from being lost.
Non-Compliant Code
unsigned int *ptr = 0xcfcfcfcf; ... unsigned int number = ptr + 1; unsigned int *ptr2 = ptr;
Compliant Solution
union intpoint { unsigned int *pointer; unsigned int number; } intpoint; ... intpoint mydata = 0xcfcfcfcf; ... unsigned int num = mydata.number + 1; unsigned int *ptr = mydata.pointer;
The non-compliant code leads to many possible conversion errors and additionally overflow. All of these are avoided by using a union.
Accessing Memory-Mapped Addresses*
Note: This is a bad idea. The following is a description of how to properly execute a bad idea.
Often times in low level, kernel, and graphics code you will need to access memory at a specific locations. This means you are going to have to make a literal integer to pointer to conversion! This will make your code non-portable!
The trick here is to convince the compiler you are going to do something bad instead of just assigning a pointer to an integer.
Non-Compliant Code Example
unsigned int *ptr = 0xcfcfcfcf;
Because integers are no longer pointers this could have drastic consequences.
Compliant Solution
unsigned int * ptr = (unsigned int *) 0xcfcfcfcf;
The trick here is you are telling the compiler you really do want to do this bad thing. If on your system pointers are typecast to something other than an unsigned int, then you want to use the type they are defined to be instead of unsigned int.
Credits:
- I used this little tutorial to help me figure out the particulars of unions, as they are not often used. Read it here
- Even more of my ideas came from the more recent comp.lang.c FAQ. Read it here