Course contentsShow
← C
Lesson 407 of 1,2196. Arrays and StringsFree lesson

Declaring 2D arrays: Rows and Columns

Declaring 2D arrays: Rows and Columns

What you'll learn: How to define a grid-like structure in C memory using two sets of square brackets.

Thinking in Grids

Up until now, you have used arrays as simple lists—a single row of lockers side-by-side. But what if you need to represent a chessboard, a spreadsheet, or a map? In C, we do this using 2D arrays.

Think of a 2D array like a high-rise apartment building. To find a specific unit, you can't just provide one number. You need to know which floor the unit is on and then which door number it is on that specific floor. In programming terms, we call these Rows and Columns.

The Syntax

To declare a 2D array, you provide the data type, a name, and two sets of square brackets. The first bracket defines the number of rows (vertical), and the second defines the number of columns (horizontal).

// Declaring a grid with 3 rows and 4 columns
int myGrid[3][4];

In the example above, myGrid acts like a table. It has 3 horizontal rows stacked on top of each other, and each of those rows contains 4 individual integer slots. This creates a total of 12 storage spaces (3 * 4 = 12).

Visualizing the Layout

When you write int screen[5][10], you are telling the computer to set aside enough space for 50 integers. Conceptually, you should visualize it like this:

  • The first number [5] tells you how many "lists" you have.
  • The second number [10] tells you how many items are inside each list.

It is helpful to always repeat the mantra: "Rows first, Columns second." If you get these swapped in your head, your data will still be stored, but your logic for navigating maps or tables will feel "sideways."

Why it matters

By using two dimensions, you can organize data more naturally. Instead of calculating a complex index in a giant list of 100 items, you can simply say "Go to row 5, column 2." It makes your code much easier to read and maintain when dealing with any data that naturally fits into a table format.

Key takeaway

A 2D array is declared using type name[rows][columns], creating a grid-based coordinate system for your data.