# 3.3: Multidimensional Arrays

$$\newcommand{\vecs}{\overset { \rightharpoonup} {\mathbf{#1}} }$$ $$\newcommand{\vecd}{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}}$$$$\newcommand{\id}{\mathrm{id}}$$ $$\newcommand{\Span}{\mathrm{span}}$$ $$\newcommand{\kernel}{\mathrm{null}\,}$$ $$\newcommand{\range}{\mathrm{range}\,}$$ $$\newcommand{\RealPart}{\mathrm{Re}}$$ $$\newcommand{\ImaginaryPart}{\mathrm{Im}}$$ $$\newcommand{\Argument}{\mathrm{Arg}}$$ $$\newcommand{\norm}{\| #1 \|}$$ $$\newcommand{\inner}{\langle #1, #2 \rangle}$$ $$\newcommand{\Span}{\mathrm{span}}$$ $$\newcommand{\id}{\mathrm{id}}$$ $$\newcommand{\Span}{\mathrm{span}}$$ $$\newcommand{\kernel}{\mathrm{null}\,}$$ $$\newcommand{\range}{\mathrm{range}\,}$$ $$\newcommand{\RealPart}{\mathrm{Re}}$$ $$\newcommand{\ImaginaryPart}{\mathrm{Im}}$$ $$\newcommand{\Argument}{\mathrm{Arg}}$$ $$\newcommand{\norm}{\| #1 \|}$$ $$\newcommand{\inner}{\langle #1, #2 \rangle}$$ $$\newcommand{\Span}{\mathrm{span}}$$$$\newcommand{\AA}{\unicode[.8,0]{x212B}}$$

# 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 [][] - two dimensions are not specified, and this will cause a compiler error.

#include <iostream>
using namespace std;
int main()
{
int a[][] = { {{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[] = {{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[] = { {{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.