Pointers & Memory · beginner · ~10 min

Pointers and arrays

Pass an array with its length and visit exactly its elements.

Overview

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.

Core concepts

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.

Lesson

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.

Code examples

#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

Line by line

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.

Practice tasks

  1. Trace the total after each addition.
  2. Solve Sum an array.
  3. Solve Fill an array; leave elements outside the requested range unchanged.
  4. Optional transfer: Sum via pointer walking.

Summary

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.

Practice with these exercises