so I have a pointer that points to an array of pointers!
int **matrixPtr;
matrixPtr = new int*[5];
for(i=0; i<5; ++i){
matrixPtr[i]= new int[5];
}
I'm wondering if this is the proper way to free up the memory!
for(i=0; i<5; ++i){
delete [] matrixPtr[i];
}
delete [] matrixPtr;
Thanks!
No problem. It's right! You deallocated in the reverse order that you allocated! I don't even think there's another way to do that.
Yes and no. Yes, it's the right way to manually free the memory if you have to allocate it manually like you did.
But no, you should avoid manual allocation and deallocation of 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 inner or outer dimension or both at compiletime. In C++14 std::dynarray
could become an option, too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With