Wednesday 7 August 2013

Pointers Without Pointer Variables

Since a pointer variable is nothing but a variable holding 4 bytes memory address (at least on 32-bit addressing), I had a thought that non-pointer variables which can hold 4-bytes of data can be used in place of pointer variables. This post shows how this can be achieved.
The code example below uses an unsigned integer variable in order to store memory addresses to point the integer array.

#include 

int main(int argc, char **argv)
{
        int num[] = {1, 2, 3, 4, 5};
        unsigned int ptr;
        int i;
        ptr = (unsigned int) num;
        for (i = 0; i < 5; i++)
        {
                printf("%p - %d\n\n", (void *) ptr, *(int *)(ptr));
                ptr = ptr + 4;
        }
        return 0;
}



The same concept can be used to use non-pointer variable for pointing other datatypes. After all, its about correct type-casting and since 4 bytes datatype can hold memory addresses, pointer is not always necessary. It must be noted that the increment would be different for different datatypes. Since integer requires 4 bytes, ptr is incremented in this example. If we had character array, then ptr would have to be increased by 1 since char type requires 1 byte.

However, pointers are there to make our life easy. It was just for fun :)