C++: Create a Two-Dimensional Array at Runtime

Bjarne-stroustrup
 

Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.

With language built-in facilities:

#include <iostream>
#include <istream>
#include <ostream>

int main()
{
	// read values
	int dim1, dim2;
	std::cin >> dim1 >> dim2;

	// create array
	double* array_data = new double[dim1*dim2];
	double** array = new double*[dim1];
	for (int i = 0; i < dim1; ++i)
	array[i] = array_data + dim2*i;

	// write element
	array[0][0] = 3.5;

	// output element
	std::cout << array[0][0] << std::endl;

	// get rid of array
	delete[] array;
	delete[] array_data;
}

Using std::vector from the standard library:

#include <iostream>
#include <istream>
#include <ostream>
#include <vector>

int main()
{
	// read values
	int dim1, dim2;
	std::cin >> dim1 >> dim2;

	// create array
	std::vector<std::vector<double> > array(dim1, std::vector<double>(dim2));

	// write element
	array[0][0] = 3.5;

	// output element
	std::cout << array[0][0] << std::endl;

	// the array is automatically freed at the end of main()
}

Using boost::multi_array:

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

typedef boost::multi_array<double, 2> two_d_array_type;

int main()
{
	// read values
	int dim1, dim2;
	std::cin >> dim1 >> dim2;

	// create array
	two_d_array_type A(boost::extents[dim1][dim2]);

	// write elements
	A[0][0] = 3.1415;

	// read elements
	std::cout << A[0][0] << std::endl;
}

SOURCE

Content is available under GNU Free Documentation License 1.2.