Search code examples
c++arrayspointersdelete-operator

How to delete this 2-dimensional array of pointers? Making a destructor


malla = new Celula**[n + 2];  
for(int i = 0 ; i < n + 2 ; ++i){  
     malla[i] = new Celula*[m + 2];
     for(int j = 0 ; j < m + 2 ; ++j){
         malla[i][j] = new Celula[m];
     }
}

I'm making this code and I allocate memory like this (I want a n*m array of pointers to Celula, is okay? Now I need a destructor.

Now I don't know how to access to an object in this array and:

malla[i][j].setestado(true);

doesn't work.


Solution

  • Seriously consider the advice of @konrad's . If anyhow you want to go with raw array's , you can do :

    To deallocate :

     for(int i = 0 ; i < n + 2 ; ++i)
     {
     for(int j = 0 ; j < m + 2 ; ++j) delete[] malla[i][j] ;
     delete[] malla[i];
     }
     delete[] malla;
    

    To access the object :

     malla[i][j][_m].setestado(true);
    

    Edit :

    if malla[i][j] is pointer to simply object then destructor/deallocation will look like :

     for(int i = 0 ; i < n + 2 ; ++i)
     {
     for(int j = 0 ; j < m + 2 ; ++j) delete malla[i][j] ;
     delete[] malla[i];
     }
     delete[] malla;
    

    Access object/member can be done like : (*malla[i][j]).setestado(true); or malla[i][j]->setestado(true);