Learn/C/14. Pointers and memory
Lesson 14 of 15
Sign in

C, lesson 14

Pointers and memory

Every variable lives somewhere in memory, and that somewhere has a numeric address. A pointer is a variable that stores an address. Pointers are what make C fast and flexible: they let functions change the caller's data, let you walk through arrays, and let you ask for memory while the program runs. They are also where most C bugs live, so this lesson goes slowly.

Address and dereference

  • int *p declares p as "pointer to int".
  • &score is the address-of operator: "where does score live?"
  • *p dereferences the pointer: "the int stored at that address". You can read it and assign to it.

2 exercises to try what you just read.

Exercise 1

Temperature range

Press Ctrl Enter or Check to test your code.

Exercise 2

Undo history

Press Ctrl Enter or Check to test your code.

A pointer that points nowhere should hold nullptr (C23; older code uses NULL). Dereferencing a null pointer, or a pointer to memory that no longer exists, is undefined behaviour and usually crashes.

Letting a function change your variables

Arguments are copied, so a function can't change the caller's variables directly. Pass their addresses instead. This is exactly what scanf has been doing all along.

This is also how a C function "returns" several results: it takes output parameters.

const and pointers

const int *p means "a pointer to an int I promise not to change through p". Use it for parameters a function only reads, such as an array of input values. It documents the intent and lets the compiler catch mistakes.

Pointers and arrays

An array name used in an expression turns into a pointer to its first element. Adding 1 to a pointer moves it to the next element, not the next byte, so *(a + i) and a[i] are the same thing:

Subtracting two pointers into the same array gives the distance between them in elements.

Asking for memory: malloc and free

Local variables disappear when their function returns, and arrays need a size fixed in advance. When you only learn the size while the program runs, ask for memory from the heap with malloc (in <stdlib.h>):

Rules that keep you out of trouble:

  1. Always check the result of malloc for a null pointer.
  2. Every malloc needs exactly one matching free. Forgetting it is a memory leak; freeing twice corrupts the heap.
  3. Never use memory after freeing it. Setting the pointer to nullptr right after free makes that mistake easier to spot.
  4. sizeof *values keeps the size correct even if you later change the element type.

Growing a block: realloc

realloc(ptr, new_size) resizes a block, moving it if necessary and keeping the old contents. It can fail and return a null pointer while leaving the old block intact, so store the result in a temporary first:

Doubling the capacity each time it fills up keeps the number of realloc calls small. This is how growable lists in other languages work under the hood.

Further reading

  • cppreference: Pointer declaration
  • cppreference: malloc
  • cppreference: realloc
  • cppreference: free
  • GNU C Manual: Pointers

Write void min_max(const int *values, size_t n, int *lo, int *hi), which stores the smallest and largest of the n values through the two output pointers.

Read a count n (at least 1), allocate an array of exactly n ints with malloc, read the readings into it, call min_max, and print the result. Free the array before returning.

An editor records every action as a number. Read integers until the input ends; you don't know how many there will be. Store them in a dynamic array that starts with capacity 4 and doubles with realloc whenever it is full. Then print how many there were, and the actions in reverse order (the order "undo" would visit them), using a pointer that walks backwards through the array.

If there are no actions, the second line is Undo: -.

int score = 10;
int *p = &score;     // p holds the address of score
*p = 25;             // write through the pointer
printf("%d\n", score);   // 25
void swap(int *a, int *b) {
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

int x = 1, y = 2;
swap(&x, &y);        // now x is 2 and y is 1
int a[4] = {3, 1, 4, 1};
for (int *q = a; q < a + 4; q++) {
    printf("%d ", *q);
}
int n = 1000;
int *values = malloc(n * sizeof *values);   // room for n ints
if (values == nullptr) {
    return EXIT_FAILURE;                     // out of memory
}
values[0] = 42;                              // use it like an array
free(values);                                // give it back when done
values = nullptr;
int *bigger = realloc(values, new_capacity * sizeof *values);
if (bigger == nullptr) {
    free(values);
    return EXIT_FAILURE;
}
values = bigger;
Input:
5
12 -3 8 21 0
Output:
Min: -3
Max: 21
Range: 24
Input:
3 1 4 1 5
Output:
Count: 5
Undo: 5 1 4 1 3