Pointers in C explained
What a pointer is, how & and * work, and why C uses pointers to change variables, share arrays and build data structures.
A pointer is a variable that holds a memory address. &x gives the address of x; *p follows the pointer to the value it points at.
Pointers let a function change the caller's variables, pass big data without copying it, and link data together (lists, trees). A pointer that points at nothing should be NULL; following a NULL pointer crashes the program.
The easiest way to understand pointers is to watch them: step through the visualization below and follow the arrows.
Example
#include <stdio.h>
void add_bonus(int *score) {
*score += 10;
}
int main(void) {
int score = 50;
int *p = &score;
add_bonus(p);
printf("%d %d\n", score, *p);
return 0;
}
Output:
60 60
Watch it run: A pointer holds an address