Lesson 3 of 3 · Pointers · 2 min read · Updated
Pointers and arrays
Why an array turns into a pointer the moment you pass it anywhere.
In most expressions, an array name becomes the address of its first element. That is why arr and &arr[0] are the same thing.
int arr[3] = {10, 20, 30};
int *p = arr; /* no & needed */
printf("%d\n", *p); /* 10 */
printf("%d\n", *(p + 1)); /* 20 */
printf("%d\n", p[1]); /* 20 — same thing */
p[1] is defined as *(p + 1). Array subscripting is pointer arithmetic with friendlier notation — which is why you can use [] on a pointer and * on an array.
Note
p + 1 does not add one byte — it moves forward by one int, which is usually four bytes. Pointer arithmetic counts in elements, not bytes, and the compiler works out the size from the type.
Why array parameters lose their size
/* These two declarations mean exactly the same thing.
The [] is a convenience for the reader, nothing more. */
void print_all(int arr[], int n);
void print_all(int *arr, int n);
Warning
A function receiving an array gets only a pointer — the length is gone. sizeof(arr) inside the function gives the size of a pointer, not of the array. Always pass the length as a separate parameter.
If int *p = arr; and each int is 4 bytes, what does p + 1 point to?
Create a free account to save your progress, or sign in.