It's hacky, but there's a method that simplifies both the memory layout (potentially helping the cache) as well as the cleanup, at the cost of a messy looking initialization. The idea is to allocate all the memory in one single chunk, set up pointers of the first array to point into the rest of the buffer as if it were a series of independent arrays. Here's the basic idea, minus fancies (such as templatizing the function):
double** Allocate2DArray(unsigned int width, unsigned int height){ char* buffer = new char[sizeof(double*) * width + sizeof(double) * width * height]; double** firstDimension = reinterpret_cast<double**>(buffer); double* secondDimension = reinterpret_cast<double*>(buffer + sizeof(double*) * width); double** firstDimensionEnd = firstDimension + width; while (firstDimension < firstDimensionEnd) { *firstDimension = secondDimension; firstDimension += 1; secondDimension += height; } return reinterpret_cast<double**>(buffer);}void Deallocate2DArray(double** array){ //Note: I'm not sure the reinterpret_cast back into what the //array was allocated as is necessary, but I'm doing it just to //be safe. delete [] reinterpret_cast<char*>(array);}int main(){ double** array= Allocate2DArray(4, 3); array[0][0] = 5.0; array[3][2] = 7.0; //etc. Deallocate2DArray(array);}
Now I'm more inclined to encourage the method that I'm pretty confident is used by Boost::MultiArray, which is to just allocate an ordinary single-dimension array, wrap it up in a class, and then do the appropriate multiplications and additions within the subscript operator's ([]) body. (Or even better, just use Boost::MultiArray itself!) However, the method above does have the benefit of requiring no multiplications, at the cost of a little bit extra memory for the first dimension array of pointers. In some cases this might be better, but I wouldn't be surprised if it wasn't. Wrapping all this up in a class also has plenty of other benefits, such as being able to store the size/shape of the multi-dimensioned array.
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke