cpointerspointer-arithmetic

Pointer Arithmetic


Does anyone have any good articles or explanations (blogs, examples) for pointer arithmetic? Figure the audience is a bunch of Java programmers learning C and C++.


Solution

  • First, the binky video may help. It's a nice video about pointers. For arithmetic, here is an example:

    int * pa = NULL;
    int * pb = NULL;
    pa += 1; // pa++. behind the scenes, add sizeof(int) bytes
    assert((pa - pb) == 1);
    
    print_out(pa); // possibly outputs 0x4
    print_out(pb); // possibly outputs 0x0 (if NULL is actually bit-wise 0x0)
    

    (Note that incrementing a pointer that contains a null pointer value strictly is undefined behavior. We used NULL because we were only interested in the value of the pointer. Normally, only use increment/decrement when pointing to elements of an array).

    The following shows two important concepts

    On a practical example. Suppose you write a function and people provide you with an start and end pointer (very common thing in C++):

    void mutate_them(int *begin, int *end) {
        // get the amount of elements
        ptrdiff_t n = end - begin;
        // allocate space for n elements to do something...
        // then iterate. increment begin until it hits end
        while(begin != end) {
            // do something
            begin++;
        }
    }
    

    ptrdiff_t is what is the type of (end - begin). It may be a synonym for "int" for some compiler, but may be another type for another one. One cannot know, so one chooses the generic typedef ptrdiff_t.