Arrays and Pointers
Moving through an array with a pointer.
5 minute read
Big idea
An array's name works like a pointer to its first element, and arr[i] is really "start at arr, move i elements along". Pointers and arrays are two views of the same memory.
The idea
int a[4] = {10, 20, 30, 40};
int *p = a; // same as int *p = &a[0];
Adding to a pointer moves it by whole elements, not bytes. If p points at a[0], then p + 2 points at a[2] — C multiplies by sizeof(int) for you.
| Expression | Means | Value |
|---|---|---|
a[2] | the element at index 2 | 30 |
*(a + 2) | follow the address 2 elements along | 30 |
*(p + 2) | the same, through p | 30 |
p[2] | pointers can use [ ] too | 30 |
In fact a[i] is defined as *(a + i).
Walking an array with a pointer
*p++ reads the value then moves the pointer — ++ on the pointer, used after *.
Passing arrays to functions
When you pass an array to a function, C passes the address of its first element — not a copy of the whole array. Two consequences:
- The function can change the caller's array.
- The function can't tell how long the array is, so you pass the length too.
#include <stdio.h>
void double_all(int *arr, int n) {
for (int i = 0; i < n; i++) {
arr[i] *= 2;
}
}
int main(void) {
int nums[5] = {1, 2, 3, 4, 5};
double_all(nums, 5);
for (int i = 0; i < 5; i++) {
printf("%d ", nums[i]);
}
printf("\n");
return 0;
}output
2 4 6 8 10Run and edit it in the app.
int *arr and int arr[] mean exactly the same thing in a parameter list.
Watch the array change
int a[5] = {5, 10, 15, 20, 25}; int *p = a + 1; What is *(p + 2)?
Think of it like
Houses on a street. The street name gets you to the first house; "3 doors down" gets you to the fourth. a + 3 is "3 doors down from the start".
🕷️ Spidey-sense: Swinging down 5th Avenue, I don't count bricks — I count buildings.
p + 1is the next building, however wide it is. C does the brick-counting for me.
Key terms
- Pointer arithmetic — Adding to or subtracting from a pointer moves it by whole elements.
- Array decay — An array name becoming a pointer to its first element when used in an expression or passed to a function.
Check yourself
int a[4]; int *p = a; p points at…
*(a + 3) is the same as…
When you pass an array to a function, C passes…