Module 0 · Lesson 14 of 42

Pointer arithmetic, const, and pointers to pointers

Move pointers with arithmetic, protect the pointed-to object or the pointer with const, and use pointers to pointers for argv and out-parameters.

  • Beginner to advanced
  • 7 min read
  • 15 min lab
What you will need

Ubuntu 24.04 (WSL2, VM or container) with gcc and gdb installed, and a text editor. No extra hardware is required for this lesson.

Your place in the module
By the end you can 3 objectives
  • Read pointer declarations, including the const variants, using the right-to-left rule.
  • Perform pointer arithmetic with p + n, p++ and pointer subtraction, and state the type of the result.
  • Explain when a pointer to a pointer is needed, using argv and out-parameters as examples.
Video coming soonPointer arithmetic, const, and pointers to pointers
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Pointers and dereferencing
  • A pointer is a variable that holds an address; & makes an address and * follows it.
  • C passes every argument by value, including pointers, but a pointer lets a function reach and change a caller's object.
  • int *p, q; declares p a pointer and q an int; NULL marks a pointer that points at nothing, distinct from the '\0' string terminator.
01

Pointer arithmetic

4 min read

You can now take an address, store it in a pointer, and read or write the object through *. This lesson adds pointer arithmetic, const with pointers, and pointers to pointers, answering how you move pointers and what const and the second star change.

is the operation that turns a pointer into a way of walking over a block of memory. If p points at an int, then p + 1 points at the next int in memory, and p + n points n ints ahead. The compiler scales the offset by sizeof(*p), so in bytes p + n advances n * sizeof(*p) bytes:

c
int a[5] = {11, 22, 33, 44, 55};
int *p = &a[0];           /* or simply p = a */

printf("%d\n", *p);        /* 11 */
printf("%d\n", *(p + 1));  /* 22, one int later */
printf("%d\n", *(p + 3));  /* 44, three ints later */

Because scaling is automatic, you never multiply by sizeof(int) yourself. If p were a double *, then p + 1 would advance by sizeof(double), typically 8 bytes, and the same code would still read the next element. This is the entire point: the code reads correctly for any pointed-to type.

The pointer itself can also move. The increment and decrement operators p++ and p-- move p one element forward or back, and are the idiomatic way to walk a buffer:

c
int a[] = {11, 22, 33, 44, 55, 0};
int *p = &a[0];

while (*p != 0) {       /* walk until the sentinel */
    printf("%d\n", *p);
    p++;                /* advance one int */
}

Subtracting one pointer from another gives the number of elements between them, not the number of bytes. The result has type , and it is well defined only when both pointers point into the same array. A pointer version of strlen uses exactly this:

c
size_t my_strlen(const char *s)
{
    const char *p = s;
    while (*p != '\0')
        p++;
    return (size_t)(p - s);   /* count of characters */
}

Pointers into the same array can also be compared with the relational operators <, <=, > and >=, so a loop can test p < end instead of using a sentinel. One special pointer is the one-past-the-end pointer, the address just after the last element of an array: a + 5 for a five-element array. You may form it and compare against it, but reading or writing *(a + 5) is undefined behaviour.

Step by stepWhat p + n actually computes
  1. Take the type: the compiler looks at the pointed-to type of p, say int.

  2. Measure one element: it reads sizeof(*p), the size of one int.

  3. Scale the offset: it multiplies the integer n by that size, giving the byte offset.

  4. Add the bytes: it adds the byte offset to the address held in p.

  5. Produce a pointer: the result is a pointer of the same type, n elements further along.

Pointer arithmetic is defined only while you stay inside one array, or one element past its end. Forming a pointer that lands outside that range, by a wild subtraction or a loop that runs too far, is undefined behaviour even if you never dereference it. This is the rule that makes pointer bugs so dangerous: the mistake may not crash immediately.

An array walked by pointer arithmetichigha[4]55a[3]44a[2]33a[1]22lowa[0]11higha[4]55a[3]44a[2]33a[1]22lowa[0]11
An array of five ints laid out in memory, and how p + 2 moves two elements to point at the third int.
Walk a buffer with p++ and compare against indexed access
int main(void)
{
    int a[] = {11, 22, 33, 44, 55, 0};
    int *p = a;
    printf("*(p+1) = %d, *(p+3) = %d\n", *(p + 1), *(p + 3));
    printf("walk with p++:  ");
    while (*p != 0) { printf("%d ", *p); p++; }
    printf("\n");
    printf("indexed access: ");
    for (int k = 0; k < 5; k++) printf("%d ", a[k]);
    printf("\n");
    printf("p - a = %td elements\n", p - a);
    return 0;
}
learner@embeddex:~/lab$ # compile it
learner@embeddex:~/lab$ gcc -o arith arith.c
learner@embeddex:~/lab$ # the p++ walk and indexed access print identical values; p - a counts 5
 elements
learner@embeddex:~/lab$ ./arith
*(p+1) = 22, *(p+3) = 44
walk with p++:  11 22 33 44 55
indexed access: 11 22 33 44 55
p - a = 5 elements
02

const and pointers

3 min read

In the last lesson const guarded a scalar parameter. With pointers it can guard two different things, and the position of the keyword tells them apart. There are three forms:

c
const int *p;        /* pointer to const int: cannot write *p */
int *const p;        /* const pointer: cannot reassign p */
const int *const p;  /* both: cannot write *p, cannot reassign p */

The first, const int *p, means p points at an int you promise not to modify. You can read *p, and you can point p at another int, but you cannot write through it, and the compiler rejects any attempt. This is the form to use for a function that inspects but must not change its argument, which is exactly how my_strlen above declared its parameter const char *s.

The second, int *const p, means the pointer itself is fixed. You can write *p freely, but you cannot make p point elsewhere, so p++ is a compile-time error. The third combines both.

The clean way to read any of these is right to left. Start at the variable name and read outward, crossing the * symbols in order: const int *p reads "p is a pointer to an int that is const", and int *const p reads "p is a const pointer to an int". const protects whatever is immediately to its right when read that way: in const int *p the const sits before the int, protecting the int; in int *const p it sits before the p, protecting the pointer.

The compiler is strict about this because removing const silently would let a program break its own promise. Assigning a const int * to an int * discards the qualifier and is a constraint violation, so the compiler must diagnose it (gcc reports "discards const qualifier"), because the new pointer could then modify the supposedly constant object:

c
const int n = 100;
int *p = &n;     /* error: discards const, could write through p */

The pointer-to-const declaration is also how the standard library advertises its guarantees. strlen is declared size_t strlen(const char *s);, which promises the function will not modify your string and lets it accept both writable and read-only strings, including string literals.

The three const pointer formsconst int *int * constconst int *constWrite *pnoyesnoReassign pyesnonoReads aspointer toconst intconst pointerto intconst pointerto const int
The three const placements and what each one locks: the object, the pointer, or both.
03

Pointers to pointers

4 min read

Because a pointer is just a variable holding an address, it too lives at some address, and you can take the address of it with &. The result is a :

c
int x = 3490;
int  *p = &x;     /* p points at x */
int **q = &p;     /* q points at p */

printf("%d\n", **q);   /* follow q, then follow p: 3490 */

Each & adds one level of indirection, and each * removes one. &x has type int *, &p has type int **, and **q unwinds both levels back to the int. The type spells it out: int **q means "q is a pointer to a pointer to an int".

A pointer to a pointer exists for three concrete reasons. The first is the command-line arguments to main, which the next lesson develops. The second parameter of int main(int argc, char **argv) is a char **, a pointer to an array of char * strings, which is how a program receives a list of text arguments whose length varies at run time. The second reason is an out-parameter that sets a caller's pointer. If a function must give back a pointer, for example to return a newly allocated buffer or a found node, the caller passes the address of its own pointer and the function writes through it:

c
int find_target(int **out)
{
    static int target = 42;
    *out = &target;      /* write the caller's pointer */
    return 0;
}

The third reason is arrays of strings, a table of text where each row is itself a pointer to a char array. A function that takes an array of strings is written with a char ** parameter precisely because the array decays to a pointer to its first element, and that first element is itself a char *, giving a pointer to a pointer.

The const rules compose the same way. int *const *q means "q is a pointer to a const pointer to an int": you may move q and read the final int, but you may not modify the intermediate pointer that q points at. Getting these levels right is a matter of applying the right-to-left reading twice.

The chain x, p, qhighqholds the address of ppholds the address of xlowxholds 3490highqholds the address of ppholds the address of xlowxholds 3490
The chain x, p, q in memory: x holds 3490, p holds the address of x, and q holds the address of p.
Ask what each star removes

When a double pointer confuses you, count the stars. q is int **, *q is int * (the pointer p), and **q is int (the value x). Each dereference peels off one level of indirection and changes the type accordingly.

Follow a pointer to a pointer and read argv
learner@embeddex:~/lab$ # q is int **: it holds the address of p, and **q unwinds both levels
learner@embeddex:~/lab$ cat ptrptr.c
#include <stdio.h>
int main(int argc, char **argv)
{
    int x = 3490;
    int *p = &x;
    int **q = &p;
    printf("**q = %d  (q -> p -> x)\n", **q);
    printf("argc = %d, argv[1] = %s\n", argc, argv[1]);
    return 0;
}
learner@embeddex:~/lab$ # compile it
learner@embeddex:~/lab$ gcc -o ptrptr ptrptr.c
learner@embeddex:~/lab$ # argv is char **, a pointer to an array of strings; argv[1] is the firs
t argument
learner@embeddex:~/lab$ ./ptrptr hello
**q = 3490  (q -> p -> x)
argc = 2, argv[1] = hello

Key takeaways

  • p + n advances n * sizeof(*p) bytes, and subtracting two pointers into one array yields a ptrdiff_t element count.
  • const T * protects the pointed-to object, T * const protects the pointer, and const T * const protects both.
  • A pointer to a pointer is how a function sets a caller's pointer, and how argv and arrays of strings are represented.
Reflect
  1. Explain to a colleague, in two sentences: read pointer declarations, including the const variants, using the right-to-left rule.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close