3维阵列的释放 [英] Deallocation of 3 dimensional array

查看:127
本文介绍了3维阵列的释放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个三维阵列是这样的:

I am creating a three dimensional array like this:

GLfloat ***tgrid;
//other code in between here
tgrid = new GLfloat**[nx];
for(int i = 0; i < nx; i++)
{
    tgrid[i] = new GLfloat*[ny];
    for(int j = 0; j < ny; j++)
    {
        tgrid[i][j] = new GLfloat[nz];
    }
}

这是否意味着我应该释放这样的记忆:

Does this mean i should deallocate the memory like this:

for(int i = 0; i < nx; i++)
{
    for(int j = 0; j < ny; j++)
    {
        delete [] tgrid[i][j];
    }
    delete [] tgrid[i];
}
delete [] tgrid;

我知道,他们都应该在反转以去,但我不知道我这样做是正确......这个问题似乎正确吗?

I know that they are supposed to go in "reverse" order but I'm not sure I'm doing it right ... Does this seem correct?

推荐答案

由于我的回答也是肯定的,我会跟进K-BALLO的回答对如何使用平面阵列中的小例子,存储一组的多尺寸数据:

Since my answer is also yes, I will follow up K-ballo's answer with a minimal example of how to use a flat array to store a set of multi-dimension data:

存放GLfloat指针和尺寸类的成员:

Store the GLfloat pointer and the dimensions as members of your class:

GLfloat *tgrid;
int nx, ny, nz;

在initlaization功能:

In initlaization function:

void CreateGrid(int x, int y, int z)
{
    nx = x;
    ny = y;
    nz = z;
    tgrid = new GLfloat[nx*ny*nz];
}

您将需要始终如一地定义正确读写的索引方案:

You will need to define your indexing scheme consistently for proper read-write:

GLfloat GetValueAt(int x, int y, int z)
{

    return tgrid[ (nx*ny*z) + (nx*y) + x ]; 

}

void SetValueAt(int x, int y, int z, GLfloat value)
{

    tgrid[ (nx*ny*z) + (nx*y) + x ] = value;

}

删除是直截了当太因为tgrid只是一个平面阵列。

Deleting is straight forward too since tgrid is only a flat array.

这篇关于3维阵列的释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆