Skip to content
LumenaryAcademy
Foundations 60 min

Pointers and arrays

Addresses, dereferencing, pointer arithmetic, how arrays decay to pointers, and function pointers with qsort.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Why pointers?

Every variable lives somewhere in memory, at an address. A pointer is a variable whose value is an address. That one idea explains a great deal of C:

  • It is how a function changes its caller's variables, despite pass-by-value: you pass the address, and the function writes through it.
  • It is how C handles arrays and strings, which are passed around as the address of their first element.
  • It is how C builds every dynamic data structure (lists, trees, hash tables) and how it talks to memory it obtains at run time.
  • It is how C passes functions as values, as in the standard library's qsort.

Pointers are also the source of C's most serious bugs: following a pointer to memory that does not exist, that has been freed, or that belongs to something else. The way to use them safely is to understand them exactly, which is what this lesson is for. Higher-level languages hide pointers under the name "reference"; C shows them to you.

DefinitionsH

Addresses and pointers

Definition— pointer

A pointer of type T * holds the address of an object of type T. The unary operator & gives the address of an object, and the unary operator * (dereference) gives the object that a pointer points to. The special value NULL is a pointer that points to no object.

The same symbol * appears in two roles: in a declaration (int *p;, "p is a pointer to int") and in an expression (*p, "the int that p points to"). The declaration syntax was designed so that the declaration looks like the use. The program below takes an address, writes through it, and uses pointers to write the classic swap:

c
#include <stdio.h>

void swap(int *a, int *b) {
    int tmp = *a;   /* *a: the int that a points to */
    *a = *b;
    *b = tmp;
}

int main(void) {
    int x = 3;
    int *p = &x;            /* p holds the address of x */
    printf("x = %d, *p = %d\n", x, *p);

    *p = 10;                /* writing through the pointer changes x */
    printf("after *p = 10, x = %d\n", x);

    int a = 1, b = 2;
    swap(&a, &b);           /* pass the addresses, so swap can change a and b */
    printf("a = %d, b = %d\n", a, b);

    int *nothing = NULL;    /* a pointer that points nowhere */
    if (nothing == NULL) {
        printf("always check before dereferencing\n");
    }
    return 0;
}
text
x = 3, *p = 3
after *p = 10, x = 10
a = 2, b = 1
always check before dereferencing

swap(&a, &b) passes the addresses of a and b; inside, *a and *b are the caller's variables themselves. This is how every C function that "returns" more than one thing works.

Dereferencing NULL is undefined behaviour; on Linux it reliably crashes with a segmentation fault, because the lowest pages of the address space are never mapped. Functions that return pointers often use NULL to mean "nothing" or "failure", so checking for NULL before using such a pointer is a reflex every C programmer needs. C23 adds the keyword nullptr for the null pointer, with its own type, which avoids some ambiguities of the NULL macro.

ComputationC

Arrays and pointer arithmetic

An array is a fixed number of elements of one type, stored next to each other in memory. int rainfall[5] is 5 × 4 = 20 bytes in a row. Two rules connect arrays and pointers:

Definition— array-to-pointer conversion

In almost every expression, an array is automatically converted to a pointer to its first element: rainfall becomes &rainfall[0]. The exceptions are sizeof rainfall and &rainfall, which still see the whole array. This conversion is often called decay.

Definition— pointer arithmetic

Adding an integer n to a pointer moves it by n elements, not n bytes: if p points to an int, p + 1 points to the next int, 4 bytes further on. Subtracting two pointers into the same array gives the number of elements between them, as a ptrdiff_t. And a[i] is defined to mean exactly *(a + i).

1207235pp + 1[0] +0[1] +4[2] +8[3] +12[4] +16
The array rainfall in memory, with a pointer p holding the address of element 2. Adding 1 to p moves it one int, 4 bytes, to the right.
c
#include <stddef.h>
#include <stdio.h>

/* An array parameter is really a pointer, so the length must travel with it. */
long sum(const int *values, size_t count) {
    long total = 0;
    for (size_t i = 0; i < count; i++) {
        total += values[i];          /* values[i] means *(values + i) */
    }
    return total;
}

long sum_by_pointer(const int *begin, const int *end) {
    long total = 0;
    for (const int *p = begin; p != end; p++) {   /* p++ moves to the next int */
        total += *p;
    }
    return total;
}

int main(void) {
    int rainfall[] = {12, 0, 7, 23, 5};
    size_t n = sizeof rainfall / sizeof rainfall[0];   /* 20 bytes / 4 bytes */

    printf("elements: %zu, bytes: %zu\n", n, sizeof rainfall);
    printf("sum: %ld\n", sum(rainfall, n));
    printf("sum by pointer: %ld\n", sum_by_pointer(rainfall, rainfall + n));

    int *third = &rainfall[2];
    printf("third element: %d, and the one after it: %d\n", *third, *(third + 1));
    printf("elements between first and third: %td\n", third - rainfall);
    printf("bytes between them: %td\n", (char *)third - (char *)rainfall);
    return 0;
}
text
elements: 5, bytes: 20
sum: 47
sum by pointer: 47
third element: 7, and the one after it: 23
elements between first and third: 2
bytes between them: 8

The idiom sizeof rainfall / sizeof rainfall[0] counts the elements of an array, but only where the array itself is in scope. Once the array is passed to a function, it has decayed to a pointer, and sizeof inside the function gives the size of the pointer. GCC warns about the attempt:

c
void show(int values[]) {
    printf("inside: %zu\n", sizeof values);   /* 8: the size of an int *, not of the array */
}
text
warning: 'sizeof' on array function parameter 'values' will return size of 'int *' [-Wsizeof-array-argument]

That is why C functions take a pointer and a length, like sum(const int *values, size_t count), or a pointer to the first element and a pointer one past the last, like sum_by_pointer. The second style comes from the rule that a pointer may point one element past the end of an array (but must not be dereferenced there), which makes p != end a natural loop condition.

The %td format prints a ptrdiff_t. Casting both pointers to char * before subtracting measures the distance in bytes, because a char is one byte.

Pointers as outputs, and two-dimensional arrays

Returning a status and passing results back through pointers is the standard C way to return several values, or to report failure without a special value:

c
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>

/* Returns false for an empty array; otherwise stores the results through
   the two output pointers and returns true. */
bool min_max(const int *values, size_t count, int *min_out, int *max_out) {
    if (count == 0) {
        return false;
    }
    int lo = values[0], hi = values[0];
    for (size_t i = 1; i < count; i++) {
        if (values[i] < lo) lo = values[i];
        if (values[i] > hi) hi = values[i];
    }
    *min_out = lo;
    *max_out = hi;
    return true;
}

int main(void) {
    int temps[] = {18, 25, -3, 31, 9};
    int lo, hi;
    if (min_max(temps, 5, &lo, &hi)) {
        printf("min %d, max %d\n", lo, hi);
    }
    if (!min_max(temps, 0, &lo, &hi)) {
        printf("no values, no answer\n");
    }

    /* A 2-D array is an array of arrays, stored row after row. */
    int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
    int total = 0;
    for (int r = 0; r < 2; r++) {
        for (int c = 0; c < 3; c++) {
            total += grid[r][c];
        }
    }
    printf("grid total %d, grid[1][2] = %d\n", total, grid[1][2]);
    return 0;
}
text
min -3, max 31
no values, no answer
grid total 21, grid[1][2] = 6

A two-dimensional array such as int grid[2][3] is an array of 2 arrays of 3 ints, stored row after row (row-major order); grid[1][2] is the element 1 × 3 + 2 = 5 ints from the start. Iterating with the row index outside and the column index inside walks memory in order, which is much faster on large arrays than the other way round, because it uses the processor's caches well.

IntuitionH

const, void pointers and function pointers

const and pointers

const can apply to the pointed-to data, to the pointer, or to both, and the position of const relative to * decides which:

DeclarationCan change the data?Can change the pointer?
int *pyesyes
const int *pnoyes
int *const pyesno
const int *const pnono

Read declarations from the variable name outwards: const int *p is "p is a pointer to an int that is const". Parameters such as const int *values are a promise to the caller that the function only reads the array, and the compiler enforces it. Use const on every pointer parameter whose target you do not modify.

void pointers

A void * is a pointer to "some type, not stated". Any object pointer converts to and from void * without a cast in C. Generic library functions such as memcpy, qsort and malloc traffic in void *; you convert back to a real type before dereferencing.

Function pointers

Functions have addresses too, and a pointer to a function can be stored, passed and called. The declaration int (*f)(int) means "f is a pointer to a function taking an int and returning an int"; the parentheses around *f are essential (without them it declares a function returning int *). The standard library's qsort sorts any array by taking a comparator function pointer:

c
#include <stdio.h>
#include <stdlib.h>

static int ascending(const void *a, const void *b) {
    int x = *(const int *)a, y = *(const int *)b;
    return (x > y) - (x < y);        /* -1, 0 or 1, and no overflow */
}

static int descending(const void *a, const void *b) {
    return ascending(b, a);
}

static void print_all(const char *label, const int *v, size_t n) {
    printf("%s:", label);
    for (size_t i = 0; i < n; i++) printf(" %d", v[i]);
    printf("\n");
}

static int square(int x) { return x * x; }
static int negate(int x) { return -x; }

/* Apply f to every element: f is a pointer to a function taking and returning int. */
static void map(int *v, size_t n, int (*f)(int)) {
    for (size_t i = 0; i < n; i++) v[i] = f(v[i]);
}

int main(void) {
    int scores[] = {72, 95, 61, 88, 79};
    size_t n = sizeof scores / sizeof scores[0];

    qsort(scores, n, sizeof scores[0], ascending);
    print_all("ascending", scores, n);
    qsort(scores, n, sizeof scores[0], descending);
    print_all("descending", scores, n);

    int small[] = {1, 2, 3};
    map(small, 3, square);
    print_all("squared", small, 3);
    map(small, 3, negate);
    print_all("negated", small, 3);
    return 0;
}
text
ascending: 61 72 79 88 95
descending: 95 88 79 72 61
squared: 1 4 9
negated: -1 -4 -9

The comparator receives two const void * pointers to elements, converts them to const int *, and returns a negative, zero or positive number. (x > y) - (x < y) produces exactly −1, 0 or 1; the tempting return x - y; overflows for large values of opposite sign, a classic bug. A typedef often makes function-pointer types readable: typedef int (*transform)(int); lets you write void map(int *v, size_t n, transform f).

Worked examplesH

Pointers to pointers

A pointer is a variable, so it has an address too, and a pointer to a pointer (T **) is common in real C. You have already met one without noticing: the full form of main is

c
int main(int argc, char **argv)

where argv points to an array of pointers, each pointing to the first character of one command-line argument. argv[0] is the program's name, and argv[argc] is guaranteed to be NULL.

The other everyday use is letting a function change a caller's pointer, just as swap changed a caller's int. A tokenizer, for example, often takes const char **cursor, reads characters at *cursor, and advances the caller's pointer past what it consumed:

c
/* Skip spaces: moves the caller's pointer forward. */
void skip_spaces(const char **cursor) {
    while (**cursor == ' ') {
        (*cursor)++;          /* parentheses needed: increment the pointer, not the char */
    }
}

const char *text = "   hello";
skip_spaces(&text);           /* text now points at the 'h' */

Read **cursor from the inside out: *cursor is the caller's pointer, and **cursor is the character it points to. When the levels of indirection get confusing, draw boxes and arrows on paper, as in the figure above; experienced C programmers still do.

ExplanationH

How professionals keep pointers safe

Pointers are not going away in C, so working C programmers build habits around them:

  • Pointer and length travel together. Every function that takes an array takes its length (or an end pointer) next to it, in that order, and checks indexes against it. Many projects wrap the pair in a small struct, a "slice" or "span", so they cannot be separated.
  • Ownership is written down. For every pointer parameter and return value, the comment says who owns the memory and who must free it: "the caller owns the returned string" or "borrowed: valid until the next call". C has no syntax for ownership, so documentation and consistent naming carry it.
  • const by default. Pointer parameters are const unless the function must write through them, so a reader can see at a glance which arguments may change.
  • Initialise and clear. Every pointer starts as a valid address or NULL, and a pointer whose memory has been released is set to NULL so that a later mistake fails loudly instead of quietly.
  • Tools run all the time. AddressSanitizer in debug builds and tests, static analysers (GCC's -fanalyzer, clang-tidy, Coverity and others) in continuous integration, and fuzzing for anything that parses outside input. Studies from large vendors have attributed a large share of their serious security bugs to memory-safety errors of exactly the kinds in this lesson, which is why some projects now write new components in memory-safe languages and keep C for the rest.

None of this makes C memory-safe. It makes the remaining mistakes rarer, and much easier to find.

Common misconceptionsH

Common mistakes

Misconception

"Arrays and pointers are the same thing." An array is a block of elements; a pointer is a single variable holding an address. They behave alike in expressions because of decay, but sizeof tells them apart, an array name cannot be assigned to, and int a[10] reserves 40 bytes while int *p reserves 8.

Misconception

Returning a pointer to a local variable. int *f(void) { int x = 5; return &x; } returns the address of a variable that ceases to exist when f returns. Using the pointer afterwards is undefined behaviour; GCC warns function returns address of local variable. Return the value, use a caller-provided buffer, or allocate memory dynamically (lesson 7).

Misconception

Reading past the end of an array. C does not check indexes. rainfall[5] on a 5-element array reads whatever lies after it, silently, or crashes, or is exploited by an attacker. Loops should run i < n, never i <= n; AddressSanitizer (lesson 7) catches these mistakes at run time.

Misconception

Declaring several pointers on one line. int* a, b; declares a as a pointer and b as a plain int: the * belongs to the name, not to the type. Declare one pointer per line, or write int *a, *b;.

Misconception

Dereferencing an uninitialised pointer. int *p; *p = 3; writes to a random address. Initialise every pointer, to a valid address or to NULL.

Exercises

Exercises

All outputs below were checked by compiling and running the code with GCC.

1. Pointers and arrays

CoreComputational

Given int v[] = {5, 10, 15, 20, 25}; and int *p = v + 1;, what are the values of *(p + 2), p[-1] and &v[4] - p? Give the three numbers.

Write elements separated by commas. Order and repeats don’t matter — just like in a set!

2. Pointers and arrays

CoreComputational

What does this print?

int x = 7, y = 9;
int *q = &x;
*q += 1;
q = &y;
*q *= 2;
printf("%d %d\n", x, y);

3. Pointers and arrays

CoreComputational

Given double d[4];, what is (char *)&d[3] - (char *)&d[0]?

4. Pointers and arrays

CoreComputational

On 64-bit Linux, a program declares int data[5] in main and prints sizeof data, then passes data to void show(int values[]), which prints sizeof values. What two numbers are printed?

Write elements separated by commas. Order and repeats don’t matter — just like in a set!

5. Pointers and arrays

CoreComputational

A function should be able to move a pointer along an array but must not modify the array's elements. Which declaration fits?

Choose one

6. Pointers and arrays

StretchComputational

A colleague writes a qsort comparator for ints as return *(const int *)a - *(const int *)b;. Why does the lesson use (x > y) - (x < y) instead?

Choose one

7. Pointers and arrays

CoreHuman

What is wrong with int *make(void) { int value = 42; return &value; }?

Choose one

Further reading and resources