Delete a pointer to pointer (as array of arrays)

落爺英雄遲暮 提交于 2019-12-20 08:41:50

问题


I have this in my code:

double** desc = new double* [size_out];
for (int i = 0; i < size_out; i++)
    desc[i] = new double [size_in];

How do I delete this desc?

Should I do:

delete [] desc;

or

for (int i=0; i<size_out; i++)
    delete [] desc[i];
delete [] desc;

or

for (int i=0; i<size_out; i++)
    delete [] desc[i];
delete desc;

?


回答1:


Simple rules to follow:

  • for each allocation, there has to be a deallocation (ex1 is therefore wrong)
  • what was allocated using new should be freed using delete, using new[] should be deallocated using delete[] and using malloc should be deallocated using free (ex3 is therefore wrong)

Conclusion, ex2 is OK.




回答2:


Your code shouldn't compile. The type of an array new expression is a pointer to the type of array element being created (the value is a pointer to the first element of the allocated array).

So the type of new double**[size_out] is double ***.

Whenever you use the array form of new, you must use the array form of delete even if you only allocate an array of size one.

double*** desc = new double**[size_out];
for (int i=0; i<size_out; i++)
    desc[i] = new double*[size_in];


for (int i=0; i<size_out; i++)
    delete[] desc[i];

delete[] desc;

Note that you still haven't allocated any double, just pointers.

Did you really want this instead?

double** desc = new double*[size_out];
for (int i=0; i<size_out; i++)
    desc[i] = new double[size_in];

for (int i=0; i<size_out; i++)
    delete[] desc[i];

delete[] desc;



回答3:


Your deletion should mirror your allocation.

Since you used new [] to allocate the outer array, and new [] (in a loop) to allocate the inner arrays, do likewise for deletion. That is: your second solution is correct; delete [] the inner arrays in a loop, and finally the outer array via delete [] also.

That said, a (much, much) better solution in C++ would be to use a nested std::vector:

// Declaration and initialization:
vector<vector<double> > desc(size_out, vector<double>(size_in));

// No deletion!



回答4:


Solution 2 is the right one : each cell points to a dynamically allocated array that should be deleted using delete[]. Finally, the desc array itself should be deleted using delete[].

Bonus solution 4 : avoid using arrays and switch to std::vector<std::vector<double> >.




回答5:


I would do

for (int i=0; i<size_out; i++)
    delete [] desc[i];
delete [] desc;

for each array allocated with new [], you have a corresponding delete [].

And as Rupdolph says: stop using C-arrays, and start using std::vector. You will have less bugs (hundred times less bugs).



来源:https://stackoverflow.com/questions/4193982/delete-a-pointer-to-pointer-as-array-of-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!