Can't delete dynamically allocated multidimensional array

安稳与你 提交于 2019-12-11 07:44:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!