Skip to main content
Engineering LibreTexts

3.3: Multidimensional Arrays

  • Page ID
    39227
  • Multidimensional arrays in C++

    In C/C++, initialization of a multidimensional arrays can have left most dimension as optional. Except the left most dimension, all other dimensions must be specified.

    For example, following program fails in compilation. There are 3 dimensions in the declaration of the array [][][2] - two dimensions are not specified, and this will cause a compiler error.

    #include <iostream>
    using namespace std;
    int main() 
    { 
       int a[][][2] = { {{1, 2}, {3, 4}}, 
                        {{5, 6}, {7, 8}} 
                      }; // error 
       cout << "Sizeof the array " << sizeof(a)) << endl; 
    
       return 0; 
    } 
    

    The following 2 programs work without any error. The cout statement prints 4 times the sizeof an int - because the array has 4 members.

    // Program 1 
    #include <iostream>
    using namespace std; 
    int main() 
    { 
       int a[][2] = {{1,2},{3,4}}; // Works 
       cout << "Sizeof the array " << sizeof(a)) << endl;
       return 0; 
    } 
    

    The following works, BECAUSE there are now 2  of the dimensions specified. The cout statement prints 8 times the sizeof an int - because the array has 8 members.

    // Program 2 
    #include<stdio.h> 
    int main() 
    { 
       int a[][2][2] = { {{1, 2}, {3, 4}}, 
                         {{5, 6}, {7, 8}} 
                       }; // Works 
       cout << "Sizeof the array " << sizeof(a)) << endl;
       return 0; 
    } 
    

    Hopefully this provides some clarification on how code can determine the size of an array.

    Adapted from:
    "Initialization of a multidimensional arrays in C/C++" by HassanAliGeeks for Geeks is licensed under CC BY-SA 4.0