C/C++ Arena

Step 4 of 7

Arrays as parameters

You can pass an array to a function, which lets you write reusable tools like "sum this array" or "find this value". The parameter is written with empty brackets:

#include <stdio.h>

int count_over(int a[], int n, int limit) {
    int count = 0;
    for (int i = 0; i < n; i++) {
        if (a[i] > limit) {
            count++;
        }
    }
    return count;
}

int main(void) {
    int speeds[] = {45, 72, 51, 90, 38};
    printf("%d\n", count_over(speeds, 5, 50));
    printf("%d\n", count_over(speeds, 5, 100));
    return 0;
}
3
0

The function doesn't know the length

When you pass an array, C doesn't copy the elements. It passes the address of the first element, and nothing about the length comes along. Inside the function, a is really a pointer, and sizeof(a) gives the size of a pointer (often 4 or 8), not the array. That's why every C function that takes an array also takes its length: int a[], int n. The standard library works the same way.

Search: returning early

A linear search checks elements one by one. As soon as it finds a match, it can return right away; there's no point looking further. If the loop finishes without finding anything, the value isn't there, so the code after the loop returns a "not found" signal. Returning -1 is the usual convention, because -1 can never be a valid index.

Changes are shared

Because the function receives the array's address rather than a copy, if it changes a[i], the caller's array changes too. That's different from plain ints, and it's the subject of the next step.

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