C Pointers
A pointer stores the memory address of another variable. &x is the address of x; *p follows a pointer to the value it points at. Pointers let functions change the caller's variables.
ExampleC
#include <stdio.h>
void addOne(int *p) {
*p = *p + 1;
}
int main(void) {
int x = 10;
int *p = &x;
printf("%d\n", *p); // 10: value through the pointer
*p = 20;
printf("%d\n", x); // 20: x changed
addOne(&x);
printf("%d\n", x); // 21
int nums[3] = {1, 2, 3};
int *q = nums;
printf("%d %d\n", *q, *(q + 2)); // 1 3
return 0;
}Output
10 20 21 1 3
Arrays and pointers are closely related: the name of an array acts like a pointer to its first element, which is why *(q + 2) reaches the third item.
Quick check
What does *p mean when p is a pointer?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.