Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer to array of pointers! how to delete?

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!

like image 897
Matt Avatar asked Sep 10 '13 05:09

Matt


2 Answers

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.

like image 172
Wagner Patriota Avatar answered Nov 15 '22 10:11

Wagner Patriota


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.

like image 40
Arne Mertz Avatar answered Nov 15 '22 09:11

Arne Mertz