C Pointers and Arrays
Pointer arithmetic is moving a pointer from one array element to the next. Adding 1 moves to the next value in the row, not to the next byte.
Read the second element
p points at the first element. *(p + 1) reads the second element, so the print shows 20.
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40};
int *p = numbers;
printf("%d\n", *(p + 1));
return 0;
}Walk with a loop
A loop walks the array through the pointer. Each round reads one more element, so the prints show 10, 20, 30, then 40.
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40};
int *p = numbers;
for (int i = 0; i < 4; i++) {
printf("%d\n", *(p + i));
}
return 0;
}Move the pointer itself
The print shows the value at p, then p moves on. Each print shows the next element, so the prints read 5, 15, 25.
#include <stdio.h>
int main() {
int numbers[] = {5, 15, 25};
int *p = numbers;
printf("%d\n", *p);
p++;
printf("%d\n", *p);
p++;
printf("%d\n", *p);
return 0;
}Example
#include <stdio.h>
int main() {
int scores[] = {3, 6, 9, 12};
int *p = scores;
printf("%d\n", *p);
printf("%d\n", *(p + 2));
printf("%d\n", *(p + 3));
return 0;
}Key points
- A pointer can hold the address of the first element of an array.
- int *p = numbers; makes p point to numbers[0].
- p + 1 gives the address of the next element.
- *(p + 1) reads the second element.
- *(p + 2) reads the third element.
- Adding 1 moves by one element, not by one byte.
- A loop can walk an array with a pointer.
- p++ moves p to the next element.
p points at the first score. The first print reads that score, so it prints 3. The second print reads the third score with *(p + 2), so it prints 9. The third print reads the fourth score with *(p + 3), so it prints 12.
Note
Stay inside the array, and never read past the last element.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
If p points to numbers[0], what does *(p + 1) read?