In C, this function 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;
}
I understand that t is declared as a pointer to int, but why can it be used to access an entire array? Why not declare the parameter as something like int (*t)[n]? How does the indexing work, and where does the array length come from?
3 Answers
`int (*t)[n]` would mean something different: a pointer to an entire array of `n` integers, not a pointer to an individual integer. That type is useful for multidimensional arrays or when you specifically need to preserve the row size. For a one-dimensional array, `int *t` is the usual parameter type.
The function also does not verify `n`. Calling it with a value larger than the number of available elements causes out-of-bounds access and undefined behavior.
An `int *` is a pointer to one `int`, but it can also point to the first element of a contiguous sequence of `int` values. An array's elements are stored next to one another in memory, so once the function has the address of the first element, it can reach the others through pointer arithmetic.
`t[i]` is shorthand for `*(t + i)`. Since `t` is an `int *`, adding 1 advances by one `int`, not merely one byte.
When an array is passed to a function, it normally 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.
You can write the parameter using array notation:
int sum(int t[], int n)
or even:
int sum(int t[10], int n)
But inside a function parameter list, these are adjusted to `int *t`. The `10` does not allocate space or enforce that the caller provides exactly ten elements. It is still the caller's responsibility to ensure that at least `n` valid elements are available.
That is different from declaring a local array such as `int a[10]`, which really does reserve space for ten integers. The array-looking parameter syntax does not do that.

So an array is not actually the same type as a pointer; it just converts to one in this function-call context. An `int a[10]` has array type, while the parameter receives an `int *` pointing at `a[0]`.