free the memory of: A** mat = new A*[2];
Asked Answered
C

2

5

I defined:

A** mat = new A*[2];

but how can I delete it? With delete[] mat; or delete[] *mat;?

Chader answered 29/5, 2013 at 1:33 Comment(6)
This is exactly what RAII is good for. You wouldn't have to worry about freeing it.Carse
Use a container (smart pointer type) or write a small wrapper yourself, overloading operator() (as pointed out by chris below, I had initially recommended operator[])Expressionism
@0xC0000022L, operator() is a better choice tbh.Carse
@chris, fair point ... for multi-dimensional arrays it certainly is :)Expressionism
@0xC0000022L, Yeah, and to expand on your point, you can still use a 1D RAII container to implement it :)Carse
Similar: #14830097Carse
Y
7

It's delete[] mat; only when you do not do additional allocations. However, if you allocated the arrays inside the array of arrays, you need to delete them as well:

A** mat = new A*[2];
for (int i = 0 ; i != 2 ; i++) {
    mat[i] = new A[5*(i+3)];
}
...
for (int i = 0 ; i != 2 ; i++) {
    delete[] mat[i];
}
delete[] mat;
Yurik answered 29/5, 2013 at 1:42 Comment(1)
Good answer but its not just for 2D arrays. He could have an array of pointer to A with allocated memory (mat[i] = new A();) which would need a delete mat[i]; call instead of delete [] mat[i];. But you got it close enough :)Danie
P
2

the first one, delete[] mat

the second one would delete what the first element in the array was pointing to (which would be nothing if that is really all the code you have) it is equivalent to delete [] mat[0]

also, if the pointers in the array did end up pointing to allocated memory that you also wanted freed, you would have to delete each element manually. eg:

A** mat = new A*[2];
mat[0] = new A;
mat[1] = new A[3];

then you would need to do:

delete mat[0];
delete[] mat[1];
delete[] mat;
Publican answered 29/5, 2013 at 1:41 Comment(2)
I want to upvote you just because your username is matt. i.e. see matt's comment that A** mat should be de-allocated using for() delete[] mat[i]; and delete[] mat;. Got it @matt?Dulci
If you wrote that allocation code in the first place you'd also need to resign from your job...Alex

© 2022 - 2024 — McMap. All rights reserved.