Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 135 ยท Pointers

Pointer Arithmetic

Learn C pointer arithmetic - how p + 1 moves by whole elements, subtracting pointers with ptrdiff_t, the one-past-the-end rule, comparisons and what is undefined.

A pointer holds an address, and C lets you do a little math with it. You can add an integer to a pointer to move it forward through memory, subtract to move back, and subtract two pointers to find out how far apart they are. This is called pointer arithmetic, and it's how C code walks through arrays, strings and buffers without an index variable. Functions like strlen, memcpy and strchr are built on it.

The important twist is that pointer arithmetic counts in elements, not bytes. Adding 1 to an int * moves it to the next int, which is usually 4 bytes further on. That one rule makes pointer code short and readable, and it's also why the rules about where a pointer may point are strict. This lesson covers adding and subtracting, the ptrdiff_t type, the special "one past the end" position, pointer comparisons, and the mistakes that lead to undefined behavior.

You'll need the basics from Pointers: & takes an address, * follows one.

Adding an integer to a pointer

If p points to an element of an array, p + 1 points to the next element, p + 2 to the one after that, and p - 1 to the previous one. The compiler multiplies the integer by the size of the pointed-to type for you. You can see that by measuring the distance in bytes: converting both pointers to char * (whose elements are exactly 1 byte) and subtracting them.

C p + 1 moves by one element

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

On our server a char step is 1 byte, an int step is 4 bytes and a double step is 8 bytes, which matches sizeof for each type. *(pi + 2) reads the element two places after counts[0], which is 30. The parentheses matter: *pi + 2 would read counts[0] and add 2 to the value, giving 12.

(You'll notice the array names are assigned straight to pointers: int *pi = counts;. An array used in an expression turns into a pointer to its first element. Pointers and Arrays explains that conversion in depth.)

The compound forms work too: p += 3, p -= 2, p++ and --p all move the pointer itself, in whole elements.

Walking through an array with a pointer

Instead of a counter i and values[i], you can keep a pointer to the current element and move it forward. The loop below stops when the pointer reaches the end, which is computed once as values + count:

C Looping with a pointer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

*q++ deserves a careful look, because you'll see it constantly in C code. Postfix ++ binds tighter than unary *, so *q++ means *(q++): the expression's value is the element q pointed to before the increment, and q moves forward as a side effect. That's why the three calls print 4, 8 and 15, and q ends up at 16.

Expression Reads Then changes
*p++ the current element p moves to the next element
*++p the next element p already moved before the read
(*p)++ the current element the element's value goes up by 1
++*p the element after adding 1 the element's value goes up by 1

The const int * in the loops says "a pointer through which I only read". It doesn't stop the pointer from moving; it stops you from writing *p = ... by accident. const and Pointers covers that in detail.

Subtracting two pointers

When two pointers point into the same array, q - p gives the number of elements between them. The result has type ptrdiff_t, a signed integer type from <stddef.h>, and you print it with %td. It's negative when q comes before p.

The most common use is turning a pointer back into an index. Here a small search function returns a pointer to the match (or NULL), and the caller subtracts the array's start to get the position:

C Pointer subtraction and ptrdiff_t

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

my_strlen is essentially how the real strlen works: advance until the null terminator, then report how far you went. The subtraction already counts in elements, so for char that's characters.

Note what you can't do: adding two pointers (p + q) is a compile error, because "address plus address" has no meaning. You can add an integer to a pointer, subtract an integer from it, or subtract two pointers. Multiplying or dividing pointers is also an error.

One past the end

Look again at the loop condition p != values + count. If the array has 6 elements, values + 6 doesn't point at any element: it's the position just past the last one. C has a special rule for exactly that position:

  • You may compute a pointer one past the end of an array.
  • You may compare it with other pointers into the same array and subtract them.
  • You may not dereference it. There's no element there.

Any position further away (two past the end, or anywhere before the first element) is undefined behavior just to compute, even if you never read through it. The one-past-the-end exception exists so that loops like the one above are legal.

This leads to a pattern you'll see throughout C and C++: a range described by a pointer to its first element and a pointer one past its last, written [begin, end). The [ means "included", the ) means "excluded". Half-open ranges have nice properties: end - begin is the length, an empty range is simply begin == end, and splitting a range at mid gives two ranges [begin, mid) and [mid, end) without any + 1 or - 1 adjustments.

C Half-open ranges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Notice begin + (end - begin) / 2 for the midpoint. You can't write (begin + end) / 2, because adding pointers isn't allowed. Subtracting first gives a plain integer count, and that's safe to halve. (Binary search, which you'll write in Sorting and Searching Algorithms, uses the same trick.)

Don't loop backwards past the start. A loop like for (int *p = end - 1; p >= begin; p--) looks reasonable, but its last step computes begin - 1, a pointer before the array, which is undefined behavior. Compilers may "optimize" such loops in surprising ways. Loop backwards by testing first and decrementing inside: for (int *p = end; p != begin; ) { p--; use(*p); }.

Comparing pointers

All the comparison operators work on pointers, but with different rules:

  • == and != work for any two pointers of compatible type, and for comparing with NULL. Two pointers are equal when they point to the same place (or are both null).
  • <, <=, > and >= are only defined for pointers into the same array (including one past its end) or the same struct. Then "less than" means "earlier in the array". Comparing pointers to two unrelated variables with < is undefined, even though on typical hardware it "works".
C Comparing positions in an array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The reversal is a classic two-pointer technique: one pointer starts at each end and they move toward each other until they meet. sizeof word is 12 here (11 letters plus '\0'), so word + sizeof word - 2 is the last letter. The left < right comparison is legal because both point into word.

Looking at bytes with unsigned char *

Pointer arithmetic on an unsigned char * steps through memory one byte at a time. C explicitly allows you to look at the bytes of any object through a character pointer, which is how functions like memcpy and memcmp work. It's also a way to see how a number is stored:

C
#include <stdio.h>

int main(void) {
    unsigned int value = 0x11223344;
    const unsigned char *bytes = (const unsigned char *)&value;

    for (size_t i = 0; i < sizeof value; i++) {
        printf("byte %zu: 0x%02X\n", i, *(bytes + i));
    }
    return 0;
}

On x86-64 and most ARM systems this prints 0x44, 0x33, 0x22, 0x11: the lowest byte comes first, an order called little-endian. A big-endian machine would print them in the opposite order. The program is valid C either way; only the byte order is implementation-defined. That difference matters when you write binary files, as you'll see in Binary Files.

What is undefined

Pointer arithmetic is only defined inside one array object (a single variable counts as an array of one element). Breaking these rules is undefined behavior, which means the program may seem to work, crash, or behave differently after a compiler upgrade:

  • Computing a pointer before the first element or more than one past the last.
  • Dereferencing the one-past-the-end pointer.
  • Subtracting or ordering (<, >) pointers into two different arrays.
  • Doing arithmetic on a null pointer (NULL + 1).
  • Arithmetic on void *. Standard C forbids it because void has no size. GCC allows it as an extension and treats the size as 1; add -Wpointer-arith (or -pedantic) to get a warning. void Pointers and Generic Code shows the portable way, using char *.

There's also a practical limit: the difference between two pointers must fit in ptrdiff_t. For normal arrays that's never a concern.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. int *p points to arr[0] and sizeof(int) is 4. How many bytes does p + 3 move past p?

    Pointer arithmetic counts elements, so p + 3 moves 3 ints forward, which is 3 ร— 4 = 12 bytes.
  2. 2. With int a[] = {5, 6, 7}; int *p = a;, what does printf("%d ", *p++); printf("%d", *p); print?

    *p++ means *(p++): it yields the element p pointed to before moving, which is 5. Afterwards p points at a[1], so *p is 6.
  3. 3. Which operation on two pointers into the same array is NOT allowed?

    You can subtract pointers (giving a ptrdiff_t), compare them and test them for equality, but adding two addresses has no meaning and does not compile.
  4. 4. For int a[4];, which statement about a + 4 is true?

    a + 4 is the one-past-the-end pointer. C guarantees you can compute it and use it in comparisons and subtraction, which is what makes p != a + 4 loops legal, but there is no element to read there.
  5. 5. Which format specifier prints a ptrdiff_t value correctly?

    t is the length modifier for ptrdiff_t, and d because it is signed. %zu is for size_t and %p prints a pointer itself.

Summary

  • p + n and p - n move a pointer by n elements; the compiler multiplies by sizeof *p for you.
  • p++, p--, p += n move the pointer; *p++ reads the current element and then advances, while (*p)++ changes the element.
  • Subtracting two pointers into the same array gives the element count between them as a signed ptrdiff_t, printed with %td. hit - array turns a pointer into an index.
  • You may compute and compare the one-past-the-end pointer but never dereference it. Anything further out, or before the start, is undefined.
  • Half-open ranges [begin, end) make lengths (end - begin), empty ranges and splits simple.
  • == and != work for any pointers; < and > only within one array. Pointers can't be added, multiplied or divided.
  • unsigned char * steps through the bytes of any object; arithmetic on void * is a non-standard GCC extension.

Next: Pointers and Arrays