Definition
Memory Pointer
A pointer is a C data type that stores a memory address and is tagged with the type of the object at that address. The type tag is what makes pointer arithmetic scale: adding
1to anint*moves the address bysizeof(int)bytes, so the pointer lands on the next integer, not the next byte. A pointer lets a program access or modify a variable that is not in scope by passing a reference to it rather than a copy of its value.
Operators
The two core pointer operators
&x— the address-of operator: yields a pointer tox(e.g.int *p_a = &a;takes the address ofa).*p— the dereference operator: yields the value stored at the addressppoints to (e.g.int y = *p_a;reads the integer atp_a), and*p = vwritesvthrough the pointer.
Pointer Arithmetic
Arithmetic scaled by the pointed-to type
Arithmetic on a pointer depends on its type — equivalently, on the size of the object it addresses.
- increment (
p++): step to the address of the next object of that type;- add/subtract an integer (
p + k): the address of the object at distancek;- subtract another pointer of the same type (
p - q): the count of objects that fit between the two addresses.For a
char*the step is 1 byte; for anint*on a 64-bit platform it is typically 4 bytes; for along*it is 8 bytes. The type, not the raw byte count, is what the programmer manipulates.
Structs and the Arrow Operator
Reaching a struct field through a pointer
Passing a large
structby value to a function would copy it in full. Instead the function takes a pointer to the struct and reads only the fields it needs, which is whyvoid update_font(struct Book *book, int size) { book->fontsize = size; }is idiomatic. The->operator is syntactic sugar for(*book).title— dereference the pointer and immediately access the named member.
Why Pointers Exist
The three jobs pointers do
- pass by reference — let a function read or modify a caller’s variable without copying the whole object (the +-performance motivation);
- byte-indexed access — give fine-grained, direct control over memory, which is exactly the power that makes C unsafe;
- dynamic memory — point at objects allocated at runtime on the heap (see the memory cluster).
The cost
Nothing in the language stops a pointer from being incremented past the end of its object, freed twice, or used after its target has been deallocated — these are all memory-safety hazards and the root cause of the bugs the cluster studies.