Skip to content

Pass an Array and Its Count

The Course
•
32 min study

You have written the "add up the sessions" loop twice now. It belongs in a function, so that the daily report, the weekly report and the tests all call one sum. Moving it there reveals something C does differently from most languages: when you pass an array to a function, the function does not learn how long it is. It receives only the location of the first element. So the caller must also pass the count, and the function must trust that count. This lesson is about writing that contract down and keeping it.

Predict and run

Predict before running C
#include <stdio.h>

int sum(const int values[], int count) {
    int total = 0;
    for (int i = 0; i < count; i++) {
        total += values[i];
    }
    return total;
}

int main(void) {
    int minutes[3] = {25, 10, 15};
    printf("%d %d\n", sum(minutes, 3), sum(minutes, 0));
    return 0;
}
Check your prediction
Text
50 0

With count 3 the loop visited all three elements. With count 0 the condition was false at once, so the loop did nothing and the function returned its starting total. That is the right answer for an empty collection, and it needed no special case. Call sum(minutes, 2) and predict 35: the function only looks at the elements it was told about.

The array is not copied

Yesterday you learned that a function gets a copy of each argument. Arrays are the exception that proves the rule. Copying a large array for every call would be slow, so C passes the address of the first element instead, and an array parameter such as int values[] is really a pointer. The function reads and writes the caller's own elements. Day 5 explains pointers properly; for now, what matters is the consequence:

A function changes the caller's elements C
#include <stdio.h>

void add_break(int values[], int count) {
    for (int i = 0; i < count; i++) {
        values[i] += 5;
    }
}

int main(void) {
    int minutes[3] = {25, 10, 15};
    add_break(minutes, 3);
    printf("%d %d %d\n", minutes[0], minutes[1], minutes[2]);
    return 0;
}
Text
30 15 20

Compare that with the int parameter in the scope lesson, where the caller's value never changed. Here every element changed, because there was only ever one array.

const promises not to change it

Most array functions only read. Writing const int values[] makes that a promise the compiler enforces: an assignment such as values[0] = 0; inside sum is rejected with an error about assigning to a read-only location. The promise helps the caller, who can see from the declaration alone that their data is safe, and it helps you, because an accidental write becomes a compile error instead of a corrupted report. Use const on every array parameter that the function does not need to change.

sizeof cannot rescue you

In the previous lesson, sizeof planned / sizeof planned[0] counted the elements of an array. Inside a function that trick breaks, because the parameter is a pointer, and sizeof measures the pointer, not the caller's array:

C
int broken_count(const int values[]) {
    return sizeof values / sizeof values[0];
}

This returns the size of a pointer divided by the size of an int, for any array at all: 1 in this browser, where pointers are 4 bytes, and 2 on most 64-bit machines. Clang warns that sizeof on an array function parameter will return the size of the pointer, and a local build with -Werror stops there. The browser editor builds without warning flags, so here it runs and quietly returns the wrong length. There is no way to recover the length from inside the function. That is why every array function in this course takes a count.

The count is a precondition

A precondition is something the caller must guarantee before calling. For sum, the caller promises that count is between 0 and the number of elements that really exist. The function cannot check this, because it does not know the real size. If a caller passes 4 for a three-element array, the loop reads values[3], which is undefined behavior, exactly as in the last lesson. Write the precondition in a comment above the function, and pass the count from the same place that tracks the data, never as a number you typed by hand.

An empty collection is perfectly valid: count 0 with an array that has room for more.

The count travels with the data C
#include <stdio.h>

/* Precondition: 0 <= count <= number of elements in values. */
int sum(const int values[], int count) {
    int total = 0;
    for (int i = 0; i < count; i++) {
        total += values[i];
    }
    return total;
}

int main(void) {
    int week[7] = {0};
    int count = 0;
    printf("Empty: %d\n", sum(week, count));
    week[count] = 30;
    count++;
    week[count] = 45;
    count++;
    printf("Logged: %d\n", sum(week, count));
    return 0;
}
Text
Empty: 0
Logged: 75

The array has capacity 7 throughout, but sum only ever sees the elements that count says are real.

Practice

Exercise

Your turn

Write two functions. int count_at_least(const int values[], int count, int threshold) returns how many of the first count elements are at least threshold. void extend_all(int values[], int count, int extra) adds extra to each of the first count elements. Starting from {25, 10, 40, 20}, print the number of sessions of at least 25 minutes, extend every session by 5, print the count again, then show the empty case:

Text
Before: 2
After: 3
Empty: 0
Your workspace C
#include <stdio.h>

int main(void) {
    int minutes[4] = {25, 10, 40, 20};
    // Write your solution here.
    return 0;
}
Hint 1: the idea

Counting only reads the array, so its parameter should be const. Extending writes to it, so its parameter cannot be. Both loops are bounded by count, not by 4.

Hint 2: a first step

Write count_at_least with a found counter that starts at 0 and increases only when values[i] >= threshold. Print Before before writing the second function.

Show one solution
C
#include <stdio.h>

int count_at_least(const int values[], int count, int threshold) {
    int found = 0;
    for (int i = 0; i < count; i++) {
        if (values[i] >= threshold) {
            found++;
        }
    }
    return found;
}

void extend_all(int values[], int count, int extra) {
    for (int i = 0; i < count; i++) {
        values[i] += extra;
    }
}

int main(void) {
    int minutes[4] = {25, 10, 40, 20};
    printf("Before: %d\n", count_at_least(minutes, 4, 25));
    extend_all(minutes, 4, 5);
    printf("After: %d\n", count_at_least(minutes, 4, 25));
    printf("Empty: %d\n", count_at_least(minutes, 0, 25));
    return 0;
}
Text
Before: 2
After: 3
Empty: 0

The 20-minute session became 25 and joined the count, which shows that extend_all changed the caller's array. The const on count_at_least documents that it never does. Both functions handle count 0 without a special case. Next you will meet the array that C uses for text, where the length is marked by a special character instead of a count.

Was this article helpful?

Your response is saved on this device.