• Home
  • 5.12 Two-Dimensional Array Initialization

5.12 Two-Dimensional Array Initialization

View Categories

5.12 Two-Dimensional Array Initialization

A two-dimensional array can be initialized using nested brace-enclosed lists. Each inner list initializes one row, making the arrangement of rows and columns explicit.

#include <stdio.h>

int main(void)
{
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    for (int row = 0; row < 3; row++)
    {
        for (int col = 0; col < 3; col++)
        {
            printf("%d ", matrix[row][col]);
        }

        printf("\n");
    }

    return 0;
}

Example Output #

1 2 3
4 5 6
7 8 9

Explanation #

The declaration:

int matrix[3][3] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

creates three rows, each containing three integers. Each inner initializer corresponds to one row.

A two-dimensional array can also be initialized with a flat list:

int matrix[2][3] = {1, 2, 3, 4, 5, 6};

The elements are assigned in row-major order, producing:

1 2 3
4 5 6

If fewer initializers are supplied than there are elements, the remaining elements are initialized to zero:

int matrix[2][3] = {
    {1, 2},
    {3}
};

The resulting array is:

1 2 0
3 0 0

Two-Dimensional Array Initialization Forms #

Declaration Result
int a[2][2] = {{1, 2}, {3, 4}}; Both rows initialized explicitly
int a[2][2] = {1, 2, 3, 4}; Values assigned in row-major order
int a[2][3] = {{1}, {2}}; Remaining elements initialized to zero
int a[][2] = {{1, 2}, {3, 4}}; Row count inferred as 2

When the first dimension is omitted, the compiler infers it from the initializer. The inner dimensions must still be specified for a multidimensional array declaration.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *