Array Initialization
An array can be initialized by specifying each element between curly braces
and separating them by commas:
int arrayOfInt[5] = {0, 1, 2, 3, 4};
this holds also for multi-dimensional arrays:
int biDimensionalArray[2][3] = {0, 1, 2,
3, 4, 5};
for which there is also the alternative of separating each
dimension by using curly braces, for reading purposes only:
int biDimensionalArray2[2][3] = {
{0, 1, 2},
{3, 4, 5}
};
Also more than one dimension can be grouped together:
int triDimensionalArray[2][2][2] = {
{{0, 1},
{2, 3}},
{{4, 5},
{6, 7}}
};
In case one of the array dimensions is left unspecified, the actual
amount of memory allocated for the array is determined by the compiler
according to the number of elements provided:
int biDimensionalArray3[][3] = { 0, 1, 2,
3, 4, 5,
6, 7, 8
};
Example
#include <iostream>
using namespace std;
int main()
{
// declare and initialize arrays
int arrayOfInt[5] = {0, 1, 2, 3, 4};
int biDimensionalArray[2][3] = {0, 1, 2,
3, 4, 5};
int biDimensionalArray2[2][3] = {
{0, 1, 2},
{3, 4, 5}
};
int triDimensionalArray[2][2][2] = {
{{0, 1},
{2, 3}},
{{4, 5},
{6, 7}}
};
int biDimensionalArray3[][3] = { 0, 1, 2,
3, 4, 5,
6, 7, 8
};
// print all arrays
for(int i = 0; i < 5; i++)
cout << arrayOfInt[i] << " ";
cout << "\n\n";
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 3; j++)
cout << biDimensionalArray[i][j] << " ";
cout << endl;
}
cout << "\n\n";
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 3; j++)
cout << biDimensionalArray2[i][j] << " ";
cout << endl;
}
cout << "\n\n";
cout << "3-dimensional array:\n\n";
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 2; j++)
{
for(int k = 0; k < 2; k++)
cout << triDimensionalArray[i][j][k] << " ";
cout << endl;
}
cout << "\n\n";
}
cout << "leftmost dimension unspecified:\n\n";
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 3; j++)
cout << biDimensionalArray3[i][j] << " ";
cout << endl;
}
}
Output
0 1 2 3 4
0 1 2
3 4 5
0 1 2
3 4 5
3-dimensional array:
0 1
2 3
4 5
6 7
leftmost dimension unspecified:
0 1 2
3 4 5