Search code examples
c++pointersdelete-operator

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


I defined:

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

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


Solution

  • 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;