C/C++ Arena

Step 4 of 6

Arrays as parameters

When you pass an array to a function, the function doesn't know its length. Always pass the length too:

int sum(int a[], int n) {
    int s = 0;
    for (int i = 0; i < n; i++) s += a[i];
    return s;
}

Unlike plain ints, changes to array elements inside the function are visible to the caller (the next module explains why).

Your turn: write int index_of(int a[], int n, int target) that returns the index of the first element equal to target, or -1 if it isn't there.

Previous: Read into an array Next: Modify an array in a function