Tags C & C++

Updated on 04.06.2010

Allocating multi-dimensional arrays in C++ (and C) is not a trivial task for newbies, and many find it difficult. The concept itself isn’t really that hard to understand, but the cryptic syntax of C++ can sometimes make it far from obvious.

The important point to understand here is that in C++, a multi-dimensional array is actually an array of arrays. Thinking in these terms, the task becomes quite easy. It is best to illustrate this with an example:

#include <iostream>
#include <cstring>

using namespace std;

int main(int argc, char *argv[])
{
    unsigned i;

    // Declaration of the two-dimensional array
    // as a pointer to pointer
    //
    char** array_2D;
    unsigned ROWS = 10;
    unsigned COLUMNS = 10;

    // Allocate "main" array
    //
    array_2D = new char*[ROWS];

    // Allocate each member of the "main" array
    //
    for (i = 0; i < ROWS; ++i)
        array_2D[i] = new char[COLUMNS];

    // Fill the 6th element with a string and
    // print it out
    //
    strcpy(array_2D[5], "Hey there");
    cout << array_2D[5] << endl;

    // Deletion is performed in reversed order.
    // Pay special attention to the delete[]
    // operator which must be used to delete
    // arrays (instead of the "simple" delete)
    //
    for (i = 0; i < ROWS; ++i)
        delete[] array_2D[i];

    delete[] array_2D;

    return 0;
}

In this example, an 2-dimensional array of char is created. As you probably know, an array of char is usually used in the role of a text string in C, so a 2-dimensional array is then an array of C strings.

Dynamic allocation and reclamation of multi-dimensional arrays is not an entirely trivial task. It is also quite "dangerous", as memory leaks and/or buffer overflows may be easily produced. If all you need is an array of character strings, it is highly advised to use a vector of strings from the C++ standard library.