Best way to represent a 2-D array in C++ with size determined at run time Best way to represent a 2-D array in C++ with size determined at run time arrays arrays

Best way to represent a 2-D array in C++ with size determined at run time


The manual dynamic way:

Let's say you want an array of width*height, the most efficient way is to just use a single dimensional array:

char *matrix = new char[width*height];

To delete it:

delete[] matrix;

To access it:

char getArrayValue(char *matrix, int row, int col){  return matrix[row + col*width];}

To modify it:

void setArrayValue(char *matrix, int row, int col, char val){  matrix[row + col*width] = val;}

Boost Matrix:

Consider using boost::matrix if you can have the dependency.

You could then tie into the boost linear algebra libraries.

Here is some sample code of boost::matrix:

#include <boost/numeric/ublas/matrix.hpp>using namespace boost::numeric::ublas;matrix<char> m (3, 3);for (unsigned i = 0; i < m.size1 (); ++ i)    for (unsigned j = 0; j < m.size2 (); ++ j)        m (i, j) = 3 * i + j;

On the stack for some compilers:

Some compilers actually allow you to create arrays on the stack with runtime determined sizes. g++ is an example of such a compiler. You cannot do this by default VC++ though.

So in g++ this is valid code:

int width = 10;int height = 10; int matrix[width][height];

Drew Hall mentioned that this C99 feature is called Variable Length Arrays (VLAs) and it can probably be turned on in any modern compiler.


I usually do something like this:

char *matrix = new char [width * height];matrix[i + j * width] = 'c'; // same as matrix[i][j] = 'c';delete [] matrix;


You seem to be missing the whole point of C++ (C with classes) :-). This is the sort of use that's crying out for a class to implement it.

You could just use STL or other 3rd party class library which I'm sure would have the data structure you're looking for but, if you need to roll your own, just create a class with the following properties.

  • constructor which, given n, will just create a new n*n array of char (e.g., charray)..
  • member functions which get and set values based on x.y which simply refer to charray[x*n+y];
  • destructor which delete[]'s the array.