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

23,135

Solution 1

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);

Solution 2

Don’t use pointers.

std::vector<std::vector<Celula> > malla(n, std::vector<Celula>(m));

// …
malla[1][2].setestado(true);

Upshot: one line instead of seven, easier usage, no delete needed anywhere.

As an aside, it’s conventional to use English identifiers in code. If nothing else, this has the advantage that people can help you better if they don’t speak the same language as you.

Share:
23,135
freinn
Author by

freinn

A spanish programmer. I like math and science. Sometimes I'm rude, but I hope you can forgive me.

Updated on August 22, 2020

Comments

  • freinn
    freinn over 3 years
    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.

    • Benjamin Lindley
      Benjamin Lindley about 12 years
      I want a nm array of pointers to Celula, is okay?* -- No, that's not okay. You should use boost::multi_array<Celula, 3>
  • freinn
    freinn about 12 years
    thank you, but is homework and I have no time to do this :S:S sorry, I will use it in other cases
  • Mr.Anubis
    Mr.Anubis about 12 years
    @freinn malla[i][j] is pointer to first element of array of type Celula in your case. your way, you're accessing the first element's member to which malla[i][j] points in array. But if you want to access second element (or it's member) of array to which malla[i][j] points ? then you'll have to : malla[i][j][_m].setestado(true);
  • freinn
    freinn about 12 years
    okay sorry but in the constructor was a mistake and really is malla[i][j] = new Celula; but you are right in you understanding, thx!