1. Introduction
An often required data structure is a "dynamic multi-dimensional arrays" (usually 2-D).
There are two principal approaches:
Both approaches are illustrated below (with two versions for approach 1) using a
dynamic 2-D array example.
2. Approach 1 - Version 1
This approach simulates the 2-D array using a 1-D array. Two dimensional indexes must
therefore be calculated using the identity: (rowIndex*numCols)+colIndex.
void main(void)
{
int numRows, numCols;
int *arrayPtr;
int rowIndex, colIndex;
/* Initialise# the array with a sequence of numbers derived from the indexes. */
3. Approach 1 - Version 2
The disadvantage of the above approach is that it is not a real 2-D array in the sense that we cannot index into the array using the
standard arrayName[rowIndex][colIndex] approach used with constrained 2-D arrays. One way round this is to use a #define
statement to define INDEX(X,Y) as (X*numRows)+Y so that we can now index in using statements of the form
arrayName[INDEX(rowIndex,colIndex)] --- not quite what we would desire (some practitioners might even consider it to be a
"hack") but close!
arrayPtr[INDEX(0,0)] = 0;
4. Approach 2
If we insist on using the standard arrayName[rowIndex][colIndex] 2-D array indexing
approach then we need to do something a bit more complicated --- we need to create an
array of arrays. To do this we must use "a pointer to a pointer" to the start of the array
(i.e. **arrayName), create space for the first array and then create space for each sub
array by iterating (looping) through the first array and so on. Thus: