开发者

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. E.g. 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 i.e. 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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜