Codiqo

Learn C · lesson 53 of 60 · about 8 minutes

Declaring 2D Arrays

Store a table of values in rows and columns, and reach any cell with two indexes.

What you'll learn

  • Declare and initialise a 2D array
  • Read and change a cell with [row][col]
  • Work out the number of rows and columns

The server rack

With the backup disks moved, the report maps the server rack: 3 shelves, each with 4 slots for a machine. The slots in use are typed as a shelf and a slot, like 1 3, until end, and anything that isn't a real slot gets No slot at 9 9. Then the report draws the rack, # for a slot in use and . for a free one, and counts them: 4 of 12 slots in use. A table of shelves and slots is exactly what a 2D array holds.

Rows and columns

A 2D array is an array of arrays: a grid. int grid[2][3]; has 2 rows, each with 3 columns.

You reach a cell with two indexes, row first: grid[1][2] is row 1, column 2. Both start at 0, just like ordinary arrays.

A small grid

#include <stdio.h>

int main(void) {
    int grid[2][3] = {
        {1, 2, 3},
        {4, 5, 6},
    };
    printf("%d\n", grid[0][2]);
    printf("%d\n", grid[1][0]);
    grid[1][1] = 50;
    printf("%d\n", grid[1][1]);
    return 0;
}

Output

3
4
50

How big is it?

sizeof grid / sizeof grid[0] is the number of rows, and sizeof grid[0] / sizeof grid[0][0] is the number of columns. In memory, the rows are stored one after another, so a 2×3 grid is really six ints in a row.

Counting rows and columns

#include <stdio.h>

int main(void) {
    char seats[4][10] = {{0}};
    int rows = sizeof seats / sizeof seats[0];
    int cols = sizeof seats[0] / sizeof seats[0][0];
    printf("%d rows, %d columns, %d seats\n", rows, cols, rows * cols);
    return 0;
}

Output

4 rows, 10 columns, 40 seats

Checking a slot before using it

rack[shelf][slot] only exists for shelves 0 to 2 and slots 0 to 3, and C won't stop you writing outside the grid. So the report checks both numbers against shelves and slots, worked out with sizeof, before it sets the cell to 1. Setting the same slot twice just leaves it at 1, so the count stays right.

Tip

Think of grid[r][c] as "row r, column c", like reading a table: go down to the row, then across to the column.

Now try it yourself

This lesson is free in Codiqo, with 9 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.