Indirection and generic data

Lesson 10 of 14 · C memory foundations

A pointer to a pointer lets a function change the caller’s pointer object. Each * follows one level:

pp ──> p ──> number [3]
       *pp     **pp
#include <stdio.h>
void redirect(int **slot, int *target) { *slot = target; }
int main(void) {
    int a = 3, b = 8;
    int *p = &a;
    redirect(&p, &b);
    printf("%d\n", *p);
    return 0;
}

Output: 8. Both integers remain alive. Similarly swapping two char * variables takes pointers to those pointer variables (char **), whereas swapping integer values takes int * arguments. An array of char * is an array of pointers; the strings may have different lifetimes and ownership.

void * can hold a pointer to an object of any object type and convert back to a suitable object pointer in C. It is not a universal function pointer, cannot be dereferenced directly, and does not record the target type or size. A correct generic interface must carry that information separately. memcpy copies a specified number of bytes between nonoverlapping regions; memmove permits overlap. A generic swap needs a temporary buffer, valid appropriately sized objects, allocation-failure handling and a policy for overlapping inputs. Casting arbitrary integers to pointers is not a portable way to store values in a generic pointer container.

A self-referential record can use an incomplete type: struct Node { int value; struct Node *next; };. Two structures can point to each other after forward declarations. A complete member cannot contain itself directly, because its required size would be infinite. Such links can form graphs and cycles, so the ownership rules must cover more than syntax.

Chapter index · Course index