typestar

Pointer arithmetic in C

Walking an array with pointers instead of indexes.

int sum_with_pointers(const int *items, int n) {
    const int *end = items + n;
    int total = 0;
    for (const int *p = items; p < end; p++)
        total += *p;
    return total;
}

How it works

  1. items + n points just past the last element.
  2. Incrementing p steps one element at a time.
  3. *p reads the element under the pointer.

Keywords and builtins used here

The run, in numbers

Lines
7
Characters to type
161
Tokens
53
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 35 seconds.

Type this snippet

Step 3 of 5 in Pointers, step 3 of 25 in Pointers & memory.

← Previous Next →