问题
I can't delete the dynamically generated arrays. There is how I create them:
template <typename T>
T **AllocateDynamic2DArray(int nRows, int nCols){
T **dynamicArray;
dynamicArray = new T*[nRows];
for( int i = 0 ; i < nRows ; i++ ){
dynamicArray[i] = new T[nCols];
for ( int j=0; j<nCols;j++){
dynamicArray[i][j]= 0;
}
}
return dynamicArray;
}
And I initialize a 2D array using:
long double** h = AllocateDynamic2DArray<long double>(KrylovDim+1,KrylovDim);
I can't delete it. Here are the variations that I've tried:
delete[] h;
and it gives the error: "cannot delete objects that are not pointers" when I apply this:
for (int qq=0; qq < KrylovDim+1; qq++){
for (int ww=0; ww < KrylovDim; ww++){
delete [] h[qq][ww];
}
delete [] h[qq];
}
Is there any way for a clean delete? I'm using visual studio 2010 if it helps.
回答1:
Try this:
for (int qq=0; qq < KrylovDim + 1; qq++)
{
delete [] h[qq];
}
delete [] h;
So basically you are doing the reverse of the allocation process
for( int i = 0 ; i < nRows ; i++ ){
dynamicArray[i] = new T[nCols]; // Instead of allocating now delete !
来源:https://stackoverflow.com/questions/5836171/cant-delete-dynamically-allocated-multidimensional-array