In C/C++, initialization of a multidimensional array can have left most dimensions as optional. Except for the leftmost dimension, all other dimensions must be specified.
For example, the following program fails in compilation because two dimensions are not specified.
C++
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[][][2] = { {{1, 2}, {3, 4}},
{{5, 6}, {7, 8}} };
cout << sizeof (a);
getchar ();
return 0;
}
|
C
#include<stdio.h>
int main()
{
int a[][][2] = { {{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}
};
printf ( "%d" , sizeof (a));
getchar ();
return 0;
}
|
Output
./Solution.cpp: In function 'int main()':
./Solution.cpp:5:14: error: declaration of 'a' as multidimensional array must have bounds for all dimensions except the first
int a[][][2] = { {{1, 2}, {3, 4}},
^
./Solution.cpp:7:18: error: 'a' was not declared in this scope
cout << sizeof(a);
^
Multidimensional Array can be initialized using an initializer list as shown:
Syntax
array_name[x][y] = { {a, b, c, ... }, ........., { m, n, o ...}};
Following 2 programs work without any error.
C++
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[][2] = {{1, 2}, {3, 4}};
cout << sizeof (a);
return 0;
}
|
C
#include<stdio.h>
int main()
{
int a[][2] = {{1,2},{3,4}};
printf ( "%lu" , sizeof (a));
getchar ();
return 0;
}
|
C++
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[][2][2] = { {{1, 2}, {3, 4}},
{{5, 6}, {7, 8}} };
cout << sizeof (a);
return 0;
}
|
C
#include<stdio.h>
int main()
{
int a[][2][2] = { {{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}
};
printf ( "%lu" , sizeof (a));
getchar ();
return 0;
}
|
The below example is multidimensional array in C/C++.
C++
#include <iostream>
using namespace std;
int main() {
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;
}
|
C
#include <stdio.h>
int main() {
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;
}
|
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!