Codiqo

Learn C · lesson 55 of 60 · about 9 minutes

Grids and Functions

Pass 2D arrays to functions and let them read or change the grid.

What you'll learn

  • Write a function that takes a 2D array
  • Give the column size in the parameter
  • Change a grid inside a function

A limit on the traffic

The network can only take so many requests in a quarter, so the admin types a limit. Two functions do the work: count_over counts the readings over the limit without changing anything, Readings over 100: 3, and cap_grid cuts every reading over the limit down to it. Because cap_grid changes the report's own grid, printing traffic again afterwards shows the capped numbers: web: 80 100 100 40. A limit that isn't a number above 0 gives No traffic limit set.

The column size has to be known

When you pass a 2D array to a function, C needs to know how long each row is, so it can find the start of the next row. You give the number of columns in the parameter; the number of rows goes in a separate argument:

void show(int g[][3], int rows)

Printing a grid in a function

#include <stdio.h>

#define COLS 3

void show(int g[][COLS], int rows) {
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < COLS; c++) printf("%d ", g[r][c]);
        printf("\n");
    }
}

int main(void) {
    int a[2][COLS] = {{1, 2, 3}, {4, 5, 6}};
    show(a, 2);
    return 0;
}

Output

1 2 3
4 5 6

Functions can change the grid

Just like a 1D array, a 2D array is passed as a pointer to its first row, so a function that writes to g[r][c] changes the caller's grid. Use const in the parameter when a function should only read it.

Filling and reading

#include <stdio.h>

#define N 3

void times_table(int g[][N]) {
    for (int r = 0; r < N; r++)
        for (int c = 0; c < N; c++) g[r][c] = (r + 1) * (c + 1);
}

int total(const int g[][N]) {
    int sum = 0;
    for (int r = 0; r < N; r++)
        for (int c = 0; c < N; c++) sum += g[r][c];
    return sum;
}

int main(void) {
    int t[N][N];
    times_table(t);
    printf("%d %d\n", t[2][1], total(t));
    return 0;
}

Output

6 36

Read first, then change

Order matters here: count_over has to run before cap_grid, because once the readings are capped, none of them is over the limit any more. count_over takes const int g[][4], so it can't change the grid by mistake; cap_grid takes int g[][4], because changing it is its whole job. Both get the number of rows, 3, as a separate argument.

Tip

A #define for the grid's size keeps the array, the parameters and the loops in step. Change it in one place and everything follows.

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.