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

Initializing 2D arrays with nested braces

Initializing 2D arrays with nested braces

What you'll learn: How to use curly braces to organize and assign values to rows and columns in a two-dimensional array.

Imagine you are setting up a small egg carton that holds two rows of three eggs. When you fill this carton, you naturally think in groups: "Here are the three eggs for the first row, and here are the three eggs for the second row." Initializing a 2D array in C works exactly the same way using nested curly braces.

The "Array of Arrays" structure

In C, a 2D array is essentially an array where every element is another array. To reflect this visually in your code, we use a set of outer braces to hold the entire structure, and sets of inner braces to represent each individual row.

This method is highly recommended because it makes your code readable. Without nested braces, a long list of numbers can become a confusing "wall of data." With them, the grid structure is immediately obvious to anyone reading your program.

Coding the grid

Here is how you initialize a 2D array representing a 2×32 \times 3 grid (2 rows and 3 columns):

#include <stdio.h>

int main() {
    // A 2D array with 2 rows and 3 columns
    int grid[2][3] = {
        {10, 20, 30}, // Row 0
        {40, 50, 60}  // Row 1
    };

    // Accessing a value to verify
    // Output will be: Value at row 1, col 0 is 40
    printf("Value at row 1, col 0 is %d\n", grid[1][0]);

    return 0;
}

How the compiler sees it

When you write {{10, 20, 30}, {40, 50, 60}}, you are giving the compiler a clear map. It takes the first inner set and places those values into the first row (grid[0]). It then takes the second inner set and places them into the second row (grid[1]).

If you provide fewer values than the array can hold—for example, if you wrote {10, 20} for a row that has space for three—C will automatically fill the remaining spot in that row with a zero. This "nested" style acts as a safety net, ensuring your data stays aligned with the rows you intended.

Key takeaway

Nested braces allow you to visualize 2D arrays as a grid, where each inner pair of braces represents one horizontal row.