简体   繁体   中英

Can't delete dynamically allocated multidimensional array

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.

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 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM