C Pointer Arithmetic

C Pointer Arithmetic


Arbitrary Pointer Casting

Because most ISAs use the same number of bits as integers, it's not so uncommon to cast integers as pointers.

Here's an example.

    // Casting 32 bit int, 0x0000ffff, to a pointer
    char * ptr  = reinterpret_cast<char *>( 0x0000ffff ) ;
    char * ptr2 = reinterpret_cast<char *>( 0x0000ffff ) ;

In general, this is one of the pitfalls of C. Arbitrary pointer casting allows you to point anywhere in memory.

Unfortunately, this is not good for safe programs. In a safe programming language (say, Java), the goal is to access objects from pointers only when there's an object there. Furthermore, you want to call the correct operations based on the object's type.

Arbitrary pointer casting allows you to access any memory location and do anything you want at that location, regardless of whether you can access that memory location or whether the data is valid at that memory location.

Arrays and Pointer Arithmetic

In C, arrays have a strong relationship to pointers.

Consider the following declaration.

    int arr[ 10 ] ;