Why does an int pointer let a function access an array?

0
0
Asked By MellowCactus42 On

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

Answered By SilverMango73 On

`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.

Answered By NorthStar88 On

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.

QuietRiver17 -

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]`.

Answered By PixelHarbor6 On

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.

BrightOak31 -

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.