删除3D数组会导致分段错误

时间:2014-09-30 17:55:16

标签: c++ arrays 3d delete-operator

所以我在删除3D阵列时遇到了麻烦。它似乎在我的代码中导致分段错误。这就是我所拥有的。分段错误是由删除3D数组引起的,但我不知道为什么。

int main( int argc, char** argv ) 
{
  //variables
  ifstream inputFileStream[ argc - 2 ];
  int ***dimensions;

  //open inputFileStream and read in values...

  //creating the dynamic 3D array and reading in grey values
  dimensions = new int**[ argc - 2 ];
  for( int i = 0; i < argc - 2; i++ )
  {
      dimensions[ i ] = new int*[ width ];
      for( int j = 0; j < width; j++ )
      {
          dimensions[ i ][ j ] = new int[ height ];
          for( int k = 0; k < height; k++ )
          {
              inputFileStream[ i ] >> dimensions[ i ][ j ][ k ];
          }
      }
  }

  //do something with array

  //delete array
  for( int i = 0; i < width; i++ )
  {
      for( int j = 0; j < height; j++ )
      {
          delete[] dimensions[ i ][ j ];
      } 
      delete[] dimensions[ i ];        
  }
  delete[] dimensions;
}

2 个答案:

答案 0 :(得分:1)

分配时,您的“我”是值从0到&#39; argc-2&#39;,你的&#39; j&#39;值从0到&#39;宽度&#39;和你的&#39;&#39;值对应于&#39; height&#39;。删除时,您的&#39; i&#39;值从0到&#39;宽度&#39;以及您的&#39; j&#39;值从0到高度&#39;。然而,你在两种情况下用[i] [j]索引。这不一致。

答案 1 :(得分:0)

这是一个完整但简化的代码示例:

int main( int argc, char** argv ) 
{
    //variables
    int ***dimensions;

    //creating the dynamic 3D array and reading in grey values
    dimensions = new int**[ 10 ];
    int width = 10;
    int height = 20;
    for( int i = 0; i < 10; i++ )
    {
        dimensions[ i ] = new int*[ width ];
        for( int j = 0; j < width; j++ )
            dimensions[ i ][ j ] = new int[ height ];
    }

    for( int i = 0; i < 10; i++ )
    {
        for( int j = 0; j < width; j++ )
            delete[] dimensions[ i ][ j ];
        delete[] dimensions[ i ];        
    }
    delete[] dimensions;
}

如您所见,循环已超过10widthheight在循环逻辑中不起作用。所以问题在于你忘记了如何解开3维,错误地使用height作为内循环约束。