Pointers & Memory · intermediate · ~12 min

Double pointers

Use `T **` to let a callee modify a caller's pointer.

Lesson

A T ** is a pointer to a T *. Use it when a function needs to update the pointer itself in the caller — for example, an alloc helper that gives back a freshly allocated block.

The same logic explains int main(int argc, char **argv): argv is "a pointer to an array of pointers to char".

Code examples

int alloc_int(int **out) {
    *out = malloc(sizeof(int));
    if (!*out) return -1;
    **out = 42;
    return 0;
}
int main(void) {
    int *p = NULL;
    alloc_int(&p);
    printf("%d\n", *p);
    free(p);
}

Common mistakes

  • Forgetting that out itself is a (parameter) pointer: *out reaches the caller's int*, **out reaches the int.