Pointer arithmetic in C
Walking an array with pointers instead of indexes.
int sum_with_pointers(const int *items, int n) {
const int *end = items + n;
int total = 0;
for (const int *p = items; p < end; p++)
total += *p;
return total;
}
How it works
items + npoints just past the last element.- Incrementing
psteps one element at a time. *preads the element under the pointer.
Keywords and builtins used here
constforintreturnsum_with_pointers
The run, in numbers
- Lines
- 7
- Characters to type
- 161
- Tokens
- 53
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 35 seconds.
Step 3 of 5 in Pointers, step 3 of 25 in Pointers & memory.