Why can an int pointer be used to access an array in C?

0
0
Asked By MellowPine42 On

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?

3 Answers

Answered By SilverMaple28 On

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

NimbleQuartz6 -

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.

Answered By BrightCedar5 On

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.

Answered By QuietHarbor7 On

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.

CopperLime19 -

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?

MellowPine42 -

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.

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.