![]() |
VOOZH | about |
Prerequisite: Array Basics
In C/C++, multidimensional arrays in simple words as an array of arrays. Data in multidimensional arrays are stored in tabular form (in row major order). Below is the general form of declaring N-dimensional arrays:
:
data_type array_name[size1][size2]….[sizeN];
data_type: Type of data to be stored in the array.
Here data_type is valid C/C++ data type
array_name: Name of the array
size1, size2, …, sizeN: Sizes of the dimensions
2D arrays are arrays of single-dimensional arrays.
:
data_type array_name[x][y];
data_type: Type of data to be stored. Valid C/C++ data type.
Below is the diagrammatic representation of 2D arrays:
For more details on multidimensional and 2D arrays, please refer to Multidimensional arrays in C++ article.
Problem: Given a 2D array, the task is to dynamically allocate memory for a 2D array using new in C++.
Solution: Following 2D array is declared with 3 rows and 4 columns with the following values:
1 2 3 4 5 6 7 8 9 10 11 12
Note: Here M is the number of rows and N is the number of columns.
Method 1: using a single pointer - In this method, a memory block of size M*N is allocated and then the memory blocks are accessed using pointer arithmetic. Below is the program for the same:
1 2 3 4 5 6 7 8 9 10 11 12
Method 2: using an array of pointer: Here an array of pointers is created and then to each memory block. Below is the diagram to illustrate the concept:
Below is the program for the same:
1 2 3 4 5 6 7 8 9 10 11 12