简体   繁体   English

如何删除此二维指针数组? 制作一个析构函数

[英]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. 我正在编写此代码,并像这样分配内存(我想要一个n*m个指向Celula的指针数组,好吗?现在我需要一个析构函数。

Now I don't know how to access to an object in this array and: 现在我不知道如何访问此数组中的对象,并且:

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

doesn't work. 不起作用。

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. 结果:1行而不是7行,易于使用,无需在任何地方delete

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. 如果没有别的,那么这样做的好处是,如果人们讲的语言与您不同,他们可以更好地帮助您。

Seriously consider the advice of @konrad's . 认真考虑@konrad的建议。 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 : 如果malla[i][j]是简单对象的指针,那么析构函数/释放将看起来像:

 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); 访问对象/成员可以像这样完成: (*malla[i][j]).setestado(true); or malla[i][j]->setestado(true); malla[i][j]->setestado(true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM