(e-mail address removed) (Gregory L. Hansen) wrote in message
I'm sure I saw this mentioned somewhere, but I can't find it. How can I
dynamically allocate a multi-dimensional array in C++?
In general you shouldn't do this for raw arrays, but rather use STL
containers like std::vector or perhaps std::valarray ... std::valarray
has some associated helper classes that make it easier to "slice" a
1-D storage array to make it behave like an N-D array. An even better
choice would be to use a third party library .. check out the
Object-Oriented Numberics page for ideas:
http://www.oonumerics.org
However, if you have your heart set on doing it with raw pointers,
here is an example for a 3D matrix.
// Routine to dynamically allocate memory for a 3D array or double
// Preconditions: m==0, d1,d2,d3 > 0
// Postconditions: m points to a zero-initialized d1xd2xd3 array of
doubles
void allocate_3D(double &***m, int d1, int d2, int d3) {
if (m!=0) {
// Yikes, pointer is not NULL ... don't want to double-allocate
// emit error message and return
return;\
}
m=new double** [d1];
for (int i=0; i<d1; ++i) {
m
=new double* [d2];
for (int j=0; j<d2; ++j) {
m[j]=new double [d3];
for (int k=0; k<d3; ++k)
m[j][k]=0;
}
}
}