Initializing Multidimensional Arrays

  1. When initializing a two-dimensional array, it helps to enclose each row's initialization list in a set of braces. Here is an example:

    
    int score[4][3] = {{85, 92, 88}, {56, 49, 67}, {89, 97, 76}, {42, 56, 74}};
    The form is easy to remember since a two dimensional array is a list of lists, and a list in C++ is written with a pair of braces and with items separating each other by commas.

  2. Because of the way the C++ compiler treats spaces and line breaks, the above initialization can be written in a form resembling more like a table or a matrix:
    
    int score[4][3] = {{85, 92, 88},
                       {56, 49, 67},
                       {89, 97, 76},
                       {42, 56, 74}};
    
  3. The braces that encloses each row's initialization list are optional. The above initialization can also be written as
    
    int score[4][3] = {85, 92, 88, 56, 49, 67, 89, 97, 76, 42, 56, 74};
    The way how the above initialization list is written makes perfect sense if you remember that the values of a two-dimensional array are stored one row after another in memory.

  4. The above three different ways to initialize the array are all equivalent. Element score[0][0] is set to 85, score[0][1] is set to 92, score[0][2] is set to 88, score[1][0] is set to 56, etc.