Why can an int pointer be used to access an array in C?
Asked by
canoe_portage_notes
I'm trying to understand this C function that sums the first n elements of an array:
int sum(int *t, int n) {
int sum = 0;
for (int i = 0; i < n; ++i) {
sum += t[i];
}
return sum;
}
How can the parameter int *t refer to an entire array when it is declared as a pointer to a single int? Why don't we declare it as something like int (*t)[n] instead?
Answers
An `int *` is a pointer to an `int`, but it can point either to one integer or to the first element of a sequence of integers. Since array elements are stored next to one another, the function can use pointer arithmetic to reach the other elements.
The expression `t[i]` is shorthand for `*(t + i)`. Because `t` points to an `int`, adding 1 advances by one `int`, not merely one byte.
When an array is passed to a function, it usually converts, or โdecays,โ to a pointer to its first element. The function does not automatically know the arrayโs length, which is why `n` is passed separately.
Reply to this answer
You can write the parameter as `int t[]` or even `int t[10]`, but in a function parameter list those declarations are adjusted to mean essentially the same thing as `int *t`.
For example, these declarations are equivalent as function parameters:
`int sum(int *t, int n)`
`int sum(int t[], int n)`
`int sum(int t[10], int n)`
The `10` in the last version does not allocate an array or enforce that the caller provides exactly 10 elements. It is still just a pointer parameter, so the length must be checked or supplied separately.
Reply to this answer
`int (*t)[n]` means something different: it declares `t` as a pointer to an entire array of `n` integers. That is useful for multidimensional arrays or when you specifically need to preserve the array width, but it is not the right type for this function.
For a one-dimensional array, the function only needs a pointer to its first element and a count of how many elements it may read. The arrayโs contiguous layout makes the rest accessible through indexing.
!stage directions+: The important distinction is that the pointer does not contain the whole array or its length. It only contains the address of the first element; the caller and the function must agree on how many elements are valid.
Reply to this answer
Add your answer
Answers are reviewed before publication.
~6 chances left: So an array and a pointer arenโt actually the same type? They just behave similarly when the array is used as a function argument?
canoe_portage_notes: Exactly. An array such as `int a[10]` has type `int[10]`, not `int *`. It converts to `int *` in many expressions, including a function call like `sum(a, 10)`, but the array itself still has a fixed size.