简体   繁体   中英

How to deallocate a int*** in c++

How do I deallocate this type of 3D array in c++? I have a class that has a int*** volume as a member and I filled it this way..

    volume = new int**[xSize];
    for(int i =0; i<xSize; i++)
    {
        volume[i] = new int*[ySize];
        for(int j =0; j<ySize; j++)
        {
            volume[i][j] = new int[zSize];
            for(int k = 0; k<zSize;k++)
            {
                volume[i][j][k] = 0;
            }
        }
    }

You just reverse your actions (other than the filling of the array)

for(int i =0; i<xSize; i++)
{
    for(int j =0; j<ySize; j++)
    {
        delete[] volume[i][j];
    }
    delete[] volume[i];
}
delete[] volume;

If you can, avoid manual dynamic memory management in the first place. Eg using std::vector :

typedef std::vector<int> Vec1D;
typedef std::vector<Vec1D> Vec2D;
typedef std::vector<Vec2D> Vec3D;

Vec3D volume(xSize, Vec2D(ySize, Vec1D(zSize, 0)));

As pointed out in the comments, Boost.MultiArray is a convenient alternative.

You need to recursively iterate through all levels of the structure the same way as above (except the innermost level), and delete each element in reverse order compared to their allocation:

for(int i =0; i<xSize; i++)
{
    for(int j =0; j<ySize; j++)
    {
        delete[] volume[i][j];
    }
    delete[] volume[i];
}
delete[] volume;

In reverse.

You need the same loop structure, but for every new[] , you need a delete[] instead, and now nested stuff must occur before outer stuff.

So:

int **x = new int*[M];
for (i = 0; i < M; i++)
{
    x[i] = new int[N];
}

becomes:

for (i = 0; i < M; i++)
{
    delete [] x[i];
}
delete [] x;

Easy - Just do the steps in reverse ie delete all those volume[i][j] that you have created Then volume[i] for all i values Then volume.

It is a bit like losing your keys - you just need to retrace your steps!

The general rule is this: you need to have one matching delete[] for each and every new[] . You seen to have one instance of new int**[] , xSize instances of new int*[] , and ySize instances of new int[] .

So, you might free them all thus:

for(int i =0; i<xSize; i++)
{
    for(int j =0; j<ySize; j++)
    {
        delete[] volume[i][j];
    }
    delete volume[i];
}
delete[] volume;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM