Related Articles

Related Articles

Initialization of a multidimensional arrays in C/C++
  • Difficulty Level : Easy
  • Last Updated : 08 Oct, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


C++

filter_none

edit
close

play_arrow

link
brightness_4
code

#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

chevron_right


Following 2 programs work without any error.
 

C

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


C

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


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

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :