Dillon Welch
Dillon Welch

Reputation: 481

Deallocation of 3 dimensional array in C++

I am creating the array like this in the header file:

double (*arrayName)[b][c];

And allocating it like this in the cpp file:

arrayName= new double[a][b][c];

Where a, b, and c are constants based on the size of the data I am dealing with.

How do I deallocate this array? I tried doing the suggestion in Deallocation of 3 dimensional array, but that gives me a "Warning C4154: deletion of an array expression; conversion to pointer supplied" and causes a heap corruption error.

I'd prefer to not change to vectors as I am working with legacy code that is being repurposed but needs to stay as similar to the original as possible. I've already had to change from using static allocation to new/delete, as with the scale of the data we are working with it was overflowing the stack.

Edit: WhozCraig's method appears to be correct. I thought the way I was deallocating this array (and others like it) was my problem, but I noticed another issue in my code. I think I've fixed that, and I'll report back once my program is done rerunning (will take a day or two at least). Thanks for everyone who responded.

Edit 2: Things still aren't working 100%, but the issues are outside the scope of this question and I was able to tweak some values to get things working well enough to get the job done. Thanks again for all who responded.

Upvotes: 4

Views: 825

Answers (1)

WhozCraig
WhozCraig

Reputation: 66194

The vector-delete should work for this.

static const int b = 10;
static const int c = 10;
double (*arrayName)[b][c] = NULL;
arrayName = new double[10][b][c];
delete [] arrayName;

If you must allocate this dynamically and immediately like this, and want proof that destructors are fired correctly...

#include <iostream>
using namespace std;

class MyObj
{
public:
    MyObj() : val(1.0) {};
    ~MyObj() { cout << "~MyObj()" << endl;}

private:
    double val;
};

int main()
{
    static const int b = 3;
    static const int c = 3;
    MyObj (*arrayName)[b][c] = NULL;
    arrayName = new MyObj[3][b][c];
    delete [] arrayName;
    return 0;
}

will result in the following output (don't bother counting, there are 27 of them)

~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()

Upvotes: 10

Related Questions