Pointers & Memory · beginner · ~10 min
Pass an array with its length and visit exactly its elements.
A function that receives an array parameter usually receives a pointer to its first element. The pointer does not carry the element count. In this lesson you will pass the length explicitly and keep every loop access inside that range.
In most expressions an array is converted to a pointer to its first element; the array object and the pointer are still different things. In sum(const int *a, int n), the function needs n because it cannot recover the array length from a.
For an actual local array, sizeof a / sizeof a[0] counts elements. Inside a function whose parameter is declared int a[], sizeof a is the pointer size.
Read the half-open range [0,n). An empty range performs no reads or writes. Add into a result type large enough for the stated inputs; signed overflow is not a valid way to wrap a sum.
A function that receives an array parameter usually receives a pointer to its first element. The pointer does not carry the element count. In this lesson you will pass the length explicitly and keep every loop access inside that range.
#include <stdio.h>
long sum(const int *a, int n) {
long total = 0;
for (int i = 0; i < n; ++i) total += a[i];
return total;
}
int main(void) {
int a[] = {2, -1, 4};
printf("%ld\n", sum(a, 3));
return 0;
}
Expected output on a successful allocation, where applicable:
5
The loop reads offsets 0, 1, and 2. It stops before 3. The separate length controls the loop; the pointer alone provides no size information.
An array parameter needs a separate length. Use an exclusive end bound and handle an empty range without accessing elements. Pointer size is not array length.