Declaring Multidimensional Arrays

  1. The arrays we have been using so far has only one index. These arrays are referred to as one-dimensional (1D) arrays.

  2. Arrays can have more than one indices. These are called multidimensional arrays. They can be used to store multiple sets of data, all of the same data type.

  3. The syntax for declaring an n-dimensional (nD) array is:

    DataType ArrayName[MaxSize1][MaxSize2] ... [MaxSizeN];

    DataType specifies the type of data in the array, ArrayName is the name of the array, MaxSize1 must be either an integer literal or a named integer constant, and so is MaxSize2, etc. The first index varies from 0 to (MaxSize1 - 1), and similarly for the other indexes. Note that each index is enclosed in its own set of brackets.

  4. Examples of multidimensional arrays are,

    int score[8][3];         // exam scores for 3 exams for 8 students in a class
    char page[30][80];         // a page of text having 30 rows and 80 columns
    double threeDpicture[10][20][30];         // a 3D picture such as an MRI scan

  5. The integer array score is 2D and has two indexes, the first index ranges from 0 to 7 and the second from 0 to 2. One may think of a 2D array as having rows (going horizontally from left to right) and columns (going vertically from top to bottom) of indexed variables as shown below:
    
    score[0][0]    score[0][1]    score[0][2] 
    
    score[1][0]    score[1][1]    score[1][2] 
    
    score[2][0]    score[2][1]    score[2][2] 
    
    score[3][0]    score[3][1]    score[3][2] 
    
    score[4][0]    score[4][1]    score[4][2] 
    
    score[5][0]    score[5][1]    score[5][2] 
    
    score[6][0]    score[6][1]    score[6][2] 
    
    score[7][0]    score[7][1]    score[7][2] 
    

  6. Note that the first index labels the rows, and the second index labels the columns.

  7. The array is used to store the scores for three different exams for a total of 8 students. The indexed variables for the scores of the first student are in the first row, the indexed variables for the scores of the second student are in the second row, etc. The first column is for the first exam, and the second column for the second exam, etc. Each score must be of the integer type.

  8. So one way to interpret the above 2D array is to think of it as an array of 8 students each having a 1D array of 3 exam scores. In other words, it is really an array of arrays. Because of the way how 2D arrays are stored in memory, this is in fact the correct interpretation, as we will see next.