Memory & Pointers

a pointer

A pointer answers the question 'where is it?' rather than 'what is it?'. If a variable is a box that holds a value, a pointer is a box that holds the address of another box. It is like a slip of paper with a house number written on it: the slip is not the house, but it tells you exactly where to find it.

Concretely, a pointer is a value that is an address, stored in a variable that is just big enough to hold an address (8 bytes on a typical 64-bit machine, for ANY pointer type). Declared as int *p, the variable p holds the address of some int. You get an address with the address-of operator, p = &x, and you reach the thing it points at — the pointee — with the dereference operator, *p. Reading *p fetches the int living at that address; writing *p = 7 stores 7 there. The pointer and its pointee are two different objects: changing p (where it points) is not the same as changing *p (the value over there).

Pointers are the heart of C because they let one piece of code refer to memory another piece owns: passing a big array without copying it, letting a function modify a caller's variable, linking nodes into a list, or holding a block from the heap. They are also where most C bugs live — a pointer to memory that has been freed or never set points somewhere meaningless, and using it is undefined behaviour. A pointer is exactly as trustworthy as the address inside it.

int x = 10; int *p = &x; *p = 20; — now x is 20, because p held x's address and *p = 20 wrote through it. p itself just holds a number like 0x7ffd...; *p reaches the int over there.

p stores where x is; *p reaches the value of x.

Passing a pointer to a function still passes the address by value — C copies the address into the parameter. The function cannot change which box the caller's pointer names, but it CAN change the pointee through *p. A pointer is not the object; it is a number that locates the object.

Also called
pointer variable指標變數