C/C++ Arena

Step 4 of 10

Pointer arithmetic and arrays

An array's name turns into a pointer to its first element when you use it ("decays"). Adding 1 to a pointer moves it to the next element (not the next byte):

int a[3] = {10, 20, 30};
int *p = a;          // same as &a[0]
printf("%d\n", *(p + 1));   // 20

In fact a[i] is defined as *(a + i). That's why arrays passed to functions can be modified: the function receives a pointer to the original elements.

Your turn: write int sum(const int *p, int n) using pointer arithmetic instead of [].

Previous: Returning two results Next: null