Pointers and Functions
Pass-by-value vs pointer, the swap pattern, local propagation, returning pointers, const parameters.
Six pieces, and this is the chapter where pointers stop being an abstract exercise and become the actual reason C functions can do anything to a caller's data at all.
The swap pattern
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main(void) {
int x = 1, y = 2;
swap(&x, &y); /* x is now 2, y is now 1 */
return 0;
}Pass the addresses, dereference inside the function to read and write the caller's actual variables. Without the & and *, swap would just be shuffling local copies that vanish the moment the function returns.
Returning pointers
Returning a pointer to a local variable is a classic bug — that variable's stack frame is gone the instant the function returns, so the pointer is left dangling. Returning a pointer is only safe if it points at something that outlives the function: something malloc'd, something static, or something the caller passed in.
const parameters
void print_array(const int *arr, int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
/* arr[i] = 0; compile error — arr is read-only through this pointer */
}
}const int *arr is a promise to the caller — and to the compiler — that this function won't modify what the pointer points to, even though it has full access to it. Cheap to add, and it turns a whole category of accidental-write bugs into compile errors instead of runtime surprises.
Notes from readers
Comments — via GitHub