开发者

Delete a pointer to pointer (as array of arrays)

开发者 https://www.devze.com 2023-01-25 13:52 出处:网络
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];

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;

?


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.


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;


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!


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> >.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消