Initialization of multidimensional arrays

You can initialize a multidimensional array using any of the following techniques:
  • Listing the values of all elements you want to initialize, in the order that the compiler assigns the values. The compiler assigns values by increasing the subscript of the last dimension fastest. This form of a multidimensional array initialization looks like a one-dimensional array initialization. The following definition completely initializes the array month_days:
    static month_days[2][12] =
    {
     31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
     31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    };
  • Using braces to group the values of the elements you want initialized. You can put braces around each element, or around any nesting level of elements. The following definition contains two elements in the first dimension (you can consider these elements as rows). The initialization contains braces around each of these two elements:
    static int month_days[2][12] =
    {
     { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
     { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
    };
  • Using nested braces to initialize dimensions and elements in a dimension selectively. In the following example, only the first eight elements of the array grid are explicitly initialized. The remaining four elements that are not explicitly initialized are automatically initialized to zero.
    static short grid[3][4] = {8, 6, 4, 1, 9, 3, 1, 1};
    The initial values of grid are:
    Element Value Element Value
    grid[0][0] 8 grid[1][2] 1
    grid[0][1] 6 grid[1][3] 1
    grid[0][2] 4 grid[2][0] 0
    grid[0][3] 1 grid[2][1] 0
    grid[1][0] 9 grid[2][2] 0
    grid[1][1] 3 grid[2][3] 0
  • C Beginning of C only.

    Using designated initializers. The following example uses designated initializers to explicitly initialize only the last four elements of the array. The first eight elements that are not explicitly initialized are automatically initialized to zero.
    static short grid[3][4] = { [2][0] = 8, [2][1] = 6,
                                [2][2] = 4, [2][3] = 1 };
    The initial values of grid are:
    Element Value Element Value
    grid[0][0] 0 grid[1][2] 0
    grid[0][1] 0 grid[1][3] 0
    grid[0][2] 0 grid[2][0] 8
    grid[0][3] 0 grid[2][1] 6
    grid[1][0] 0 grid[2][2] 4
    grid[1][1] 0 grid[2][3] 1

    C End of C only.

Related information