I defined:
A** mat = new A*[2];
but how can I delete it? With delete[] mat;
or delete[] *mat;
?
I defined:
A** mat = new A*[2];
but how can I delete it? With delete[] mat;
or delete[] *mat;
?
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;
mat[i] = new A();
) which would need a delete mat[i];
call instead of delete [] mat[i];
. But you got it close enough :) –
Danie 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;
A** mat
should be de-allocated using for() delete[] mat[i];
and delete[] mat;
. Got it @matt? –
Dulci © 2022 - 2024 — McMap. All rights reserved.
operator()
(as pointed out by chris below, I had initially recommendedoperator[]
) – Expressionismoperator()
is a better choice tbh. – Carse