Step 4 of 10
Pointer arithmetic and arrays
Here's the secret behind arrays. In most expressions, an array's name automatically turns into a pointer to its first element. This is called decay. So after int a[3];, writing a gives the same thing as &a[0].
Pointer arithmetic
Adding an integer to a pointer moves it by that many elements, not bytes. If p points at an int, p + 1 points at the next int (4 bytes further on), and p + 2 two ints on. The compiler multiplies by the element size for you.
#include <stdio.h>
int main(void) {
double prices[] = {1.5, 2.25, 4.0};
double *p = prices;
printf("%.2f\n", *p);
printf("%.2f\n", *(p + 2));
p++;
printf("%.2f\n", *p);
printf("%d\n", prices[1] == *(prices + 1));
return 0;
}
1.50
4.00
2.25
1
a[i] is *(a + i)
The indexing you've been using is defined in terms of pointers: a[i] literally means "start at a, move i elements, and dereference". That's why array indexes start at 0 (*(a + 0) is the first element), and why a function that receives an array can change the caller's elements: it received a pointer to them.
Walking with a pointer
Instead of an index, you can move a pointer along the array. The loop needs to know when to stop: either count down n, or compute an end pointer one past the last element (a + n) and loop while the moving pointer hasn't reached it. Pointing one past the end is allowed; dereferencing it is not.
Your turn: write int sum(const int *p, int n) using pointer arithmetic instead of [].