CC
IntermediateLesson 8 of 18

Pointers: Addresses & Dereferencing – C

What a pointer is, call by reference, pointer arithmetic and the relationship with arrays.

Every variable lives at an address in memory. A pointer is a variable that stores such an address. With & you get the address, with * you access the value at the address (dereferencing). The pointer's type (int *) says what it points to.

#include <stdio.h>

void tausche(int *a, int *b) {
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

int main(void) {
    int x = 10;
    int *p = &x;          // p points to x
    *p = 20;              // changes x
    printf("x=%d *p=%d\n", x, *p);

    int a = 1, b = 2;
    tausche(&a, &b);      // pass addresses -> the originals are changed
    printf("a=%d b=%d\n", a, b);
    return 0;
}

Arrays and pointers are closely related: the name of an array is (almost everywhere) the address of its first element. a[i] is defined as *(a + i). In pointer arithmetic, you advance by elements, not by bytes.

#include <stdio.h>

int main(void) {
    int arr[] = {10, 20, 30, 40};
    int *p = arr;                          // same as &arr[0]
    printf("%d %d %d\n", *p, *(p + 2), p[3]);
    p++;                                   // one int further
    printf("%d\n", *p);
    for (int *q = arr; q < arr + 4; q++) printf("%d ", *q);
    printf("\n");
    printf("%td\n", &arr[3] - &arr[0]);    // difference in elements: 3
    return 0;
}

Because a function has only one return value, out parameters (pointers) are used to deliver several results:

#include <stdio.h>

void min_max(const int *a, size_t n, int *min, int *max) {
    *min = *max = a[0];
    for (size_t i = 1; i < n; i++) {
        if (a[i] < *min) *min = a[i];
        if (a[i] > *max) *max = a[i];
    }
}

int main(void) {
    int z[] = {4, -2, 9, 0, 7};
    int lo, hi;
    min_max(z, 5, &lo, &hi);
    printf("min=%d max=%d\n", lo, hi);
    return 0;
}
WarningA pointer that points nowhere should be NULL – and NULL must never be dereferenced (crash: segmentation fault). Just as dangerous: dangling pointers to variables that no longer exist, for example the address of a local variable returned as a return value.
TipRead declarations from the inside out: const int *p = "p is a pointer to a const int". const on parameters (const int *a) tells the reader and the compiler: this function only reads.