Dynamically allocated 2-d array in C++

Method 1: Use an array of arrays

#include <iostream>

int main()
{
    const size_t rows = 10, columns = 10;
    unsigned int r, c;

    /* Initialize */
    int** array1 = new int*[rows];
    for (r = 0; r < rows; ++r) {
        array1[r] = new int[columns];
    }

    /* Write */
    for (r = 0; r < rows; ++r) {
        for (c = 0; c < columns; ++c) {
            array1[r] = r * c;
        }
    }

    /* Read */
    std::cout << "7 times 8 equals " << array1[7][8] << "\n";

    /* Delete */
    for (r = 0; r < rows; ++r) {
        delete[] array1[r];
    }
    delete[] array1;
}

Method 2: Use a single array

#include <iostream>

int main()
{
    const size_t rows = 10, columns = 10;
    unsigned int r, c;

    /* Initialize */
    int* array2 = new int[rows * columns];

    /* Write */
    for (r = 0; r < rows; ++r) {
        for (c = 0; c < columns; ++c) {
            array2[r * columns + c] = r * c;
        }
    }

    /* Read */
    std::cout << "7 times 8 equals " << array2[7 * columns + 8] << "\n";

    /* Delete */
    delete[] array2;
}

Note that the formula for accessing a cell is row * columns + row.

Method 3: Use a vector of vectors

#include <iostream>
#include <vector>

int main()
{
    const size_t rows = 10, columns = 10;
    unsigned int r, c;

    /* Initialize */
    std::vector<std::vector<int> > array3(rows,
            std::vector<int>(columns));

    /* Write */
    for (r = 0; r < rows; ++r) {
        for (c = 0; c < columns; ++c) {
            array3[r] = r * c;
        }
    }

    /* Read */
    std::cout << "7 times 8 equals " << array3[7][8] << "\n";
}

Notice the use of the vector constructor that makes rows copies of a row vector.

Method 4: Use Boost.MultiArray

#include <iostream>
#include <boost/multi_array.hpp>

int main()
{
    const size_t rows = 10, columns = 10;

    /* Initialize */
    boost::multi_array<int, 2> array4(boost::extents[rows][columns]);
    boost::multi_array<int, 2>::index r, c;

    /* Write */
    for (r = 0; r < rows; ++r) {
        for (c = 0; c < columns; ++c) {
            array4[r] = r * c;
        }
    }

    /* Read */
    std::cout << "7 times 8 equals " << array4[7][8] << "\n";
}

Reference:The Boost Multidimensional Array Library