After this lesson, you will be able to: Use pointers: pointer arithmetic, pointers to arrays, pointers to functions, pass-by-reference idiom.
Pointers are the source of C's power and most of its bugs. Master them.
An address in memory.
int x = 42;int *p = &x; // p holds the address of xprintf("%d\n", *p); // 42, dereference; read what p points at*p = 100; // write through p; x is now 100printf("%d\n", x); // 100// Null pointerint *np = NULL;if (np == NULL) printf("empty\n");// *np would crash (segfault on most systems)
Arrays decay to pointers when passed.
int nums[] = {10, 20, 30};int *p = nums; // p points to nums[0]printf("%d\n", *p); // 10printf("%d\n", *(p+1)); // 20, pointer arithmeticprintf("%d\n", p[1]); // 20, same thing; nums[i] === *(nums + i)// Pass to function, length must come separatelyint sum(int *arr, size_t n) {int total = 0;for (size_t i = 0; i < n; i++) total += arr[i];return total;}sum(nums, 3);
C is pass-by-value. To modify a caller's variable, pass its address.
// WRONG, sets the local copyvoid set_zero_bad(int x) { x = 0; }// RIGHT, modifies the caller's variablevoid set_zero(int *x) { *x = 0; }int main(void) {int n = 5;set_zero_bad(n); // n still 5set_zero(&n); // n now 0return 0;}// Same pattern for swap, returning multiple values, etc.void swap(int *a, int *b) {int tmp = *a;*a = *b;*b = tmp;}
Pass behaviour like data, used by qsort.
#include <stdlib.h>int compare_ints(const void *a, const void *b) {int ai = *(const int *)a;int bi = *(const int *)b;return (ai > bi) - (ai < bi); // -1, 0, or 1}int main(void) {int nums[] = {3, 1, 4, 1, 5, 9, 2, 6};size_t n = sizeof(nums) / sizeof(nums[0]);qsort(nums, n, sizeof(int), compare_ints);return 0;}
Dereferencing NULL or uninitialized pointers. Pointer arithmetic on void*. Not allowed (size unknown). Returning a pointer to a stack local variable. Undefined behavior, the local is gone after return. Wild pointers (uninitialized). Always initialise to NULL.
Pick the C-spec answer.
Sign in and purchase access to unlock this lesson.