Pointers: Declaration, Pointer Arithmetic, Pointers and Arrays, Pointers and Functions, Dynamic Memory
This domain tests address manipulation: what a pointer stores, how arithmetic on it is scaled, and how to obtain and release heap memory safely.
Declaration and arithmetic
int *p; declares a pointer to int. &x yields the address of x, and *p names the object p points at. Pointer arithmetic scales by the pointed-to size: if p points at a[0], then p + 1 addresses a[1]. Arithmetic is defined only within an array (plus one past its end); subtracting two pointers into the same array yields an element count.
Pointers, arrays and functions
An array name in an expression decays to a pointer to its first element, so a[i] is exactly *(a + i) and &a[i] equals a + i. Passing a pointer lets a function modify the caller's data, and this is the standard way to return more than one result. A void * can hold any object address and converts implicitly in both directions.
Dynamic memory
malloc(size), calloc(n, size) (which zeroes), realloc(p, size) and free(p) come from <stdlib.h>. Check the result against NULL, use the block only while it is allocated, and free each block exactly once. No cast is needed in C, though casting a void * back to the right type is harmless.
Worked example
int a[4] = {10, 20, 30, 40};
int *p = a;
printf("%d %d\n", *(p + 2), p[3]);
This prints 30 40: p + 2 is two ints past the start, and p[3] is shorthand for *(p + 3).
Traps
- Dereferencing an uninitialised or
NULLpointer crashes or corrupts memory. sizeof(p)gives the pointer's size, not the array's.*p++increments the pointer and yields the old target;(*p)++increments the value.- Overwriting the only pointer to a
mallocblock leaks it. - Arithmetic on
void *is not standard C.