The Wayback Machine - https://web.archive.org/web/20230512155135/https://www.geeksforgeeks.org/g-fact-44/
Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Initialization of a multidimensional arrays in C/C++

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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 because two dimensions are not specified. 
 

C




#include<stdio.h>
int main()
{
  int a[][][2] = { {{1, 2}, {3, 4}},
                   {{5, 6}, {7, 8}}
                 };  // error
  printf("%d", sizeof(a));
  getchar();
  return 0;
}

C++




#include<bits/stdc++.h>
using namespace std;
int main()
{
  int a[][][2] = { {{1, 2}, {3, 4}},
                   {{5, 6}, {7, 8}} };  // error
  cout << sizeof(a);
  getchar();
  return 0;
}
 
// This code is contributed by Mayank Tyagi

Following 2 programs work without any error.
 

C




// Program 1
#include<stdio.h>
int main()
{
  int a[][2] = {{1,2},{3,4}}; // Works
  printf("%lu", sizeof(a)); // prints 4*sizeof(int)
  getchar();
  return 0;
}

C++




// Program 1
#include<bits/stdc++.h>
using namespace std;
int main()
{
  int a[][2] = {{1, 2}, {3, 4}}; // Works
  cout << sizeof(a); // prints 4*sizeof(int)
  return 0;
}
 
// This code is contributed by Mayank Tyagi

Output

16

C




// Program 2
#include<stdio.h>
int main()
{
  int a[][2][2] = { {{1, 2}, {3, 4}},
                     {{5, 6}, {7, 8}}
                   }; // Works
  printf("%lu", sizeof(a)); // prints 8*sizeof(int)
  getchar();
  return 0;
}

C++




// Program 2
#include<bits/stdc++.h>
using namespace std;
int main()
{
  int a[][2][2] = { {{1, 2}, {3, 4}},
                     {{5, 6}, {7, 8}} }; // Works
  cout << sizeof(a); // prints 8*sizeof(int)
  return 0;
}
 
// This code is contributed by Mayank Tyagi

Output

32

The below example is multidimensional array in  C/C++.

C




#include <stdio.h>
 
int main() {
 
    // code
  int a[2][3] = { { 1, 3, 2 }, { 6, 7, 8 } };
    int i, j;
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 3; j++) {
            printf("\n a[%d][%d]=%d", i, j, a[i][j]);
        }
    }
    return 0;
}

C++




#include <iostream>
using namespace std;
  
int main() {
  
    // code
    int a[2][3] = { { 1, 3, 2 }, { 6, 7, 8 } };
    int i, j;
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 3; j++) {
            cout << "\n a[" << i << "][" << j << "]=" << a[i][j];
        }
    }
    return 0;
}

Output

 a[0][0]=1
 a[0][1]=3
 a[0][2]=2
 a[1][0]=6
 a[1][1]=7
 a[1][2]=8

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 


My Personal Notes arrow_drop_up
Last Updated : 19 Mar, 2023
Like Article
Save Article
Similar Reads