Codiqo

Learn C · lesson 35 of 60 · about 8 minutes

Pointer Arithmetic

Walk the hourly load with a pointer, find the first quiet hour, and see that an array name is really a pointer to its first item.

What you'll learn

  • Add to a pointer to move along an array
  • Know that a[i] means *(a + i)
  • Walk an array with a pointer

Walking the load

The report goes through the hourly load once more, this time with a pointer: for (const int *p = hours; p < hours + HOURS; p++). p starts at the first hour, p++ moves it to the next int, and the loop stops one past the last. Each *p is added to the total for the average, and the first hour below 30% is remembered as a pointer, quiet. Subtracting quiet - hours gives how many hours along it is, so + 1 turns it into an hour number.

Arrays and pointers are close friends

In most expressions, an array's name turns into a pointer to its first item. So with int a[3]:

  • a is the same as &a[0]
  • a + 1 points to the next int (C moves by the size of an int, not one byte)
  • a[i] is shorthand for *(a + i)

That's why a function receiving an array can change it: it really receives a pointer.

Three ways to say the same thing

#include <stdio.h>

int main(void) {
    int a[] = {10, 20, 30};
    int *p = a;
    printf("%d %d %d\n", a[1], *(a + 1), *(p + 1));
    p++;
    printf("%d\n", *p);
    printf("%d\n", (int)(p - a));
    return 0;
}

Output

20 20 20
20
1

Walking a string with a pointer

#include <stdio.h>

int length(const char *s) {
    const char *start = s;
    while (*s != '\0') s++;
    return s - start;
}

int main(void) {
    printf("%d\n", length("pointer"));
    return 0;
}

Output

7

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.