Codiqo

Learn C · lesson 27 of 60 · about 8 minutes

Arrays and Functions

Find the busiest hour and throttle the rest: pass arrays to functions along with their length, and see why functions can change them.

What you'll learn

  • Write a function that takes an array
  • Pass the length separately
  • Understand that arrays aren't copied

The busiest hour

Next the report finds the busiest hour, and then throttles the CPU so no hour goes over 75%. Both are jobs for functions that take the array: index_of_max hands back where the biggest load is, and throttle lowers the loads that are too high. Because an array isn't copied when it's passed, throttle changes main's own hours.

Arrays travel without their length

A function can take an array parameter: int sum(const int a[], int n). Inside the function, C no longer knows how long the array is, so you always pass the length too.

const promises the function won't change the items, which the compiler then enforces.

Reusable array functions

#include <stdio.h>

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

void print_all(const int a[], int n) {
    for (int i = 0; i < n; i++) printf("%d ", a[i]);
    printf("\n");
}

int main(void) {
    int xp[] = {20, 35, 15};
    print_all(xp, 3);
    printf("Total XP: %d\n", sum(xp, 3));
    return 0;
}

Output

20 35 15
Total XP: 70

Arrays are not copied

Unlike an int, an array passed to a function is not copied. The function works on the caller's array, so changes stick. (You'll see why in the Pointers unit: the function really receives the array's address.)

A function that changes the array

#include <stdio.h>

void double_all(int a[], int n) {
    for (int i = 0; i < n; i++) a[i] *= 2;
}

int main(void) {
    int v[] = {1, 2, 3};
    double_all(v, 3);
    printf("%d %d %d\n", v[0], v[1], v[2]);
    return 0;
}

Output

2 4 6

Tip

Return the index of the biggest item rather than the item itself: with the index you can still read the value, a[top], and you also know where it is.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.