Easy way of creating 2-Dimensional Array in C++

An array keeps track of multiple pieces of information in linear order, a one-dimensional list. However, the data associated with certain systems (a digital image, a board game, Matrices etc.) lives in two dimensions. To visualize this data, we need a multi-dimensional data structure, that is, a multi-dimensional array.

Infact a 2-dimensional array is really nothing more than an array of arrays. Following is the c++ code for creating a 2-Dimensional Dynamic Array. In this example, i have implemented only for INT but functionality can be enhanced for multiple types using C++ Templates.

int rows,columns;

int **dynamicArray = 0;

//memory allocation for elements of rows

dynamicArray = new int *[ROWS] ;

//memory allocated for elements of each column.
for( int i = 0 ; i < ROWS ; i++ )
    dynamicArray[i] = new int[COLUMNS];

//free the allocated memory

for( int i = 0 ; i < ROWS ; i++ )
    delete [] dynamicArray[i] ;

delete [] dynamicArray ;

Besides using Pointers, there any other ways as well for creating dynamic multi-dimensional arrays e.g Vector of Vector Array or using Vector Wrapper Class but i think that “Pointers” Method is easiest one.

Leave a Reply