【问题标题】:Deallocation of 3 dimensional array3维数组的重新分配
【发布时间】:2011-11-18 09:21:37
【问题描述】:

我正在创建一个这样的三维数组:

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];
    }
}

这是否意味着我应该像这样释放内存:

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

?

我知道它们应该以“相反”的顺序进行,但我不确定我是否做得对......这看起来是否正确?

【问题讨论】:

标签: c++ arrays memory multidimensional-array memory-management


【解决方案1】:

是的,您必须以相反的顺序释放它们。否则你会在释放它们之前松开内部指针。

您有什么理由不能使用平面数组来表示您的 3 维数组?也许是 Boost.MultiArray,它可以处理多个维度并允许访问底层(平面)数组?

【讨论】:

    【解决方案2】:

    是的。 (我还有什么意思)

    【讨论】:

      【解决方案3】:

      既然我的回答也是肯定的,那我就用一个最小的例子来跟进 K-ballo 的回答,说明如何使用平面数组来存储一组多维数据:

      将 GLfloat 指针和维度存储为类的成员:

      GLfloat *tgrid;
      int nx, ny, nz;
      

      在初始化函数中:

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

      您需要一致地定义索引方案以进行正确的读写:

      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 只是一个平面数组。

      【讨论】:

      • 还要注意一对new/delete调用的性能优势。通过使用连续块而不是可能分散的小块集合可能会进一步提高性能。
      • 我确实想过这样做。哪个更能从参考位置中受益?
      【解决方案4】:

      或者,您可以使用std::vector 而不必担心newdelete

      std::vector<std::vector<std::vector<GLfloat> > > tgrid;
      tgrid.resize(nx);
      for(int i = 0; i < nx; i++) {
        tgrid[i].resize(ny);
        for(int j = 0; j < ny; i++) {
          tgrid[i][j].resize(nz);
        }
      }
      

      【讨论】:

        【解决方案5】:

        你也可以为 std::vector 实现一个包装类

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-31
          • 1970-01-01
          相关资源
          最近更新 更多