In C++ you can define multidimensional arrays with any number of dimensions. The

ANSI standard stipulates a minimum of 256 dimensions but the total number of dimensions is in fact limited by the amount of memory available.

The most common multidimensional array type is that the two-dimensional array, the so called matrix.

C++ doesn’t need any special syntax to define multidimensional arrays. On the contrary, an n-dimensional array is not any different than an array with just one dimension

whose elements are (n–1)-dimensional arrays.

Each of these elements is a float array with a size of 10, which in turn forms the rows of

the two-dimensional array, number.

This means that the same rules apply to multidimensional arrays as to one-dimensional arrays. The initialization list of a two-dimensional array thus contains the values of

the array elements, that is, the one-dimensional rows.

Arrays can have more than one dimension. The declaration for a two-dimensional array is:

type variable[size1] [size2]; // comment

Example

// a typical matrix int matrix[2][4];

That C++ does not follow the notation used in other languages of matrix [10,12].

To access an element of the matrix we use the notation:

matrix[l][2] = 10;

C++ allows you to use as many dimensions as needed (only limited by the amount of memory available). Additional dimensions can be tacked on.

four_dimensions[10][12][9][5];

Initializing multidimensional arrays is similar to initializing single-dimension arrays. A set

of curly braces {} encloses each element. The declaration:

// a typical matrix int matrix[2][4];

can be thought of as a declaration of an array of dimension 2 whose elements are arrays of

dimension 4. This array is initialized as follows:

// a typical matrix int matrix[2][4] = { {1, 2, 3, 4}, {10, 20, 30, 40} };

This is shorthand for:

matrix[0][0] = 1; matrix[0][1] = 2; matrix[0][2] = 3; matrix[0][3] = 4; matrix[1][0] = 10; matrix[1][1] = 20; matrix[1][2] = 30; matrix[1][3] = 40;

If you like this post, don’t forget to share 🙂

## No Comments

Leave a comment Cancel