C++ Multi-dimensional Arrays on the Heap

eplawless picture eplawless · Dec 4, 2008 · Viewed 25.9k times · Source

How would I go about dynamically allocating a multi-dimensional array?

Answer

Johannes Schaub - litb picture Johannes Schaub - litb · Dec 4, 2008

If you know the size of nested dimensions already, you can also literally allocate a multi dimensional array using new:

typedef int dimensions[3][4];

dimensions * dim = new dimensions[10];
dim[/* from 0 to 9 */][/* from 0 to 2 */][/* from 0 to 3 */] = 42;
delete [] dim;

instead of 10, a runtime determined value can be passed. Since it's not part of the type operator new returns, that's allowed. This is nice if you know the number of columns, but want to keep the number of rows variable, for example. The typedef makes it easier to read the code.