简体   繁体   English

如何在c ++中解除分配int ***

[英]How to deallocate a int*** in c++

How do I deallocate this type of 3D array in c++? 如何在c ++中释放这种类型的3D数组? I have a class that has a int*** volume as a member and I filled it this way.. 我有一个有一个int ***卷作为成员的类,我用这种方式填充它。

    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 : 例如,使用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. 正如评论中指出的那样, Boost.MultiArray是一种方便的替代方案。

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: 您需要以与上面相同的方式递归遍历结构的所有级别(除了最里面的级别),并且与它们的分配相比以相反的顺序delete每个元素:

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. 你需要相同的循环结构,但是对于每个new[] ,你需要一个delete[] ,而现在嵌套的东西必须外部东西之前发生。

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. 简单 - 只需反向执行步骤即删除所有已创建的volume[i][j]然后为所有i值的volume[i]然后是音量。

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[] . 一般规则是这样的:你需要为每个new[]设置一个匹配的delete[] new[] You seen to have one instance of new int**[] , xSize instances of new int*[] , and ySize instances of new int[] . 你见过有一个实例new int**[] xSize的情况下, new int*[]ySize的情况下, 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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