Initialization of a multidimensional arrays in C/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 because two dimensions are not specified.

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


Following 2 programs work without any error.

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("%ld", sizeof(a)); // prints 4*sizeof(int)
  getchar();
  return 0;
}

chevron_right


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("%d", sizeof(a)); // prints 8*sizeof(int)
  getchar();
  return 0;
}

chevron_right


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

Improved By : HassanAli



Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.