Dynamic 2-dimensional arrays
Most languages support multi-dimensional arrays. We'll
take a look at 2-dimensional arrays, but the concepts and
methods here can be expanded to higher dimensions.
We assume you have seen and used mult-dimensional arrays before.
Review of 2-D arrays
We can declare a 2-d array of characters in our program with code
char chArray1[ 3 ][ 4 ];
We conceptualize the array as a 2-dimensional figure
Memory, however, is not multi-dimensional, so what we really get
in memory is this
We use double subscripts (e.g. chArray1[ 1 ][ 2 ]) to reference
elements by row and column. The compiler uses the row number,
column number, number of columns and array type to calculate a memory
Dynamic 2-D arrays
To dynamically allocate a 2-D array, we must create an array of pointers
(the rows), in which each row element points to an array of data elements
(the columns). We need only to declare the name of the dynamic array
properly -- char **chArray2;.
This declaration is read as "chArray2 is a pointer to a pointer to char".
In reality, the compiler doesn't "know" if you plan to use chArray2 to point
to one pointer to char or as the name of the array of many pointers to char
(as we do in this case).
The code to create the 2-D array is shown below
const int ROWS = 3;
const int COLUMNS = 4;
// allocate the rows
chArray2 = new char* [ ROWS ];
// allocate the (pointer) elements for each row
for (int row = 0; row < ROWS; row++ )
chArray2[ row ] = new char[ COLUMNS ];
We can still use double subscripts to access the elements as above.
The diagram for the array is shown below
To free the array's memory, we delete the memory in the reverse order
that it was allocatd.
// delete the columns
for (int row = 0; row < ROWS; row++)
delete [ ] chArray2[ row ];
chArray2[ row ] = 0;
// delete the rows
delete [ ] chArray2;
chArray2 = 0;
Since vectors are generally preferred over arrays,
we should investigate how to declare, allocate and
delete 2-D vectors in addition to arrays.
In a 2-D array, each row is an array of elements.
In a 2-D vector, each row is a vector of elements.
We declare a 2-D vector as a "vector of vectors" as in
vector< vector< int > > intArray;
Note that this statement creates an EMPTY 2-D
vector. If we intend to use the 2-D vector
as a 2-D array, we must allocate the memory for the
vectors as we did for the dynamic 2-D array.
// allocate the rows
intArray.resize ( ROWS );
// allocate the columns
for (unsigned int i = 0; i < intArray.size( ); i++)
intArray[ i ].resize( COLUMNS );
If we intend to have variable size rows in which elements
will be placed using push_back(), then it is not necessary
to allocate the columns.
Last Modified: Monday, 28-Aug-2006 10:16:04 EDT