Pointers

Article · 3:00

A variable holding an address. Declaration, & and *, arithmetic, and the equivalence with arrays.

Every byte of memory has an address. A pointer is a variable whose value is one of those addresses, and whose type says how to interpret what is there. int *p means "p holds the address of an int" - and that type is not decoration, because it decides what *p reads and how far p + 1 moves.

Two operators. &x gives the address of x. *p dereferences - reads or writes the thing at that address. The confusion in learning them is that * appears in the declaration as part of the type and in an expression as the dereference operator, which are different jobs for one symbol.

Pointer arithmetic is scaled by the pointed-to type. If p is an int * holding address 1000, then p + 1 is 1004, not 1001, because it moves by one element. This is exactly why a[i] works: it is defined as *(a + i), and the scaling does the index arithmetic for you.

That is also the array-pointer equivalence. An array name used in an expression converts to a pointer to its first element, so a[i], *(a + i), *(i + a) and - genuinely valid, never write it - i[a] all mean the same thing. An array is not a pointer: sizeof differs, and you cannot assign to an array name. It simply decays into one almost everywhere.

Always initialise. An uninitialised pointer holds whatever was in that memory, and dereferencing it is undefined behaviour with no diagnostic.

#include <stdio.h>

int main(void)
{
    int x = 42;
    int *p = &x;          /* p holds the ADDRESS of x */

    printf("x = %d, &x = %p\n", x, (void *) &x);
    printf("p = %p, *p = %d\n", (void *) p, *p);

    *p = 99;              /* writes THROUGH the pointer */
    printf("x is now %d\n", x);

    int values[5] = {10, 20, 30, 40, 50};
    int *q = values;      /* the array decays to &values[0] */

    /* Arithmetic is scaled by the TYPE. q + 1 moves sizeof(int) bytes,
       not one byte - which is precisely why indexing works. */
    printf("%p then %p (%zu bytes apart)\n",
           (void *) q, (void *) (q + 1), sizeof(int));

    /* a[i] is DEFINED as *(a + i). All four of these are the same. */
    printf("%d %d %d %d\n", values[2], *(values + 2), *(2 + values), 2[values]);

    /* The difference between an array and a pointer, in two numbers. */
    printf("sizeof(values) = %zu, sizeof(q) = %zu\n", sizeof values, sizeof q);

    /* Walking with a pointer rather than an index. */
    for (int *it = values; it < values + 5; it++) printf("%d ", *it);
    printf("\n");

    /* Subtracting two pointers into one array gives the element count. */
    printf("distance = %td\n", (values + 4) - values);    /* 4 */

    int *uninitialised;   /* holds whatever was there */
    /* printf("%d\n", *uninitialised);   undefined behaviour */
    (void) uninitialised;
    return 0;
}