Search code examples
cpointer-arithmetic

What are convincing examples where pointer arithmetic is preferable to array subscripting?


I'm preparing some slides for an introductory C class, and I'm trying to present good examples (and motivation) for using pointer arithmetic over array subscripting.

A lot of the examples I see in books are fairly equivalent. For example, many books show how to reverse the case of all values in a string, but with the exception of replacing an a[i] with a *p the code is identical.

I am looking for a good (and short) example with single-dimensional arrays where pointer arithmetic can produce significantly more elegant code. Any ideas?


Solution

  • Getting a pointer again instead of a value:

    One usually uses pointer arithmetic when they want to get a pointer again. To get a pointer while using an array index: you are 1) calculating the pointer offset, then 2) getting the value at that memory location, then 3) you have to use & to get the address again. That's more typing and less clean syntax.

    Example 1: Let's say you need a pointer to the 512th byte in a buffer

    char buffer[1024]
    char *p = buffer + 512;
    

    Is cleaner than:

    char buffer[1024];
    char *p = &buffer[512];
    

    Example 2: More efficient strcat

    char buffer[1024];
    strcpy(buffer, "hello ");
    strcpy(buffer + 6, "world!");
    

    This is cleaner than:

    char buffer[1024];
    strcpy(buffer, "hello ");
    strcpy(&buffer[6], "world!");
    

    Using pointer arithmetic ++ as an iterator:

    Incrementing pointers with ++, and decrementing with -- is useful when iterating over each element in an array of elements. It is cleaner than using a separate variable used to keep track of the offset.


    Pointer subtraction:

    You can use pointer subtraction with pointer arithmetic. This can be useful in some cases to get the element before the one you are pointing to. It can be done with array subscripts too, but it looks really bad and confusing. Especially to a python programmer where a negative subscript is given to index something from the end of the list.