Pointer to an array of pointers! how to delete?

so I have a pointer pointing to an array of pointers!

int **matrixPtr; matrixPtr = new int*[5]; for(i=0; i<5; ++i){ matrixPtr[i]= new int[5]; } 

I wonder if this is the right way to free up memory!

  for(i=0; i<5; ++i){ delete [] matrixPtr[i]; } delete [] matrixPtr; 

Thanks!

+4
source share
2 answers

No problems. It is right! You are freed in the reverse order that you allocated! I don’t even think there is another way to do this.

+6
source

Yes and no. Yes , this is the right way to manually free memory if you need to allocate it manually, just like you do.

But no , you should avoid manually allocating and freeing memory. If you are stuck with C ++ 03 and without any smart pointers, you should use a vector of vectors. In C ++ 11 you have more options, namely smart pointers and std::array , the latter only if you know the size of the internal or external dimension, or both in compiletime. In C ++ 14, std::dynarray can also become an option.

+3
source

Source: https://habr.com/ru/post/1501409/


All Articles