【问题标题】:Dynamic 2D Array Creation Runtime Error动态 2D 阵列创建运行时错误
【发布时间】:2011-05-18 13:13:31
【问题描述】:

我正在尝试使用以下函数代码创建一个多维 int 数组:

int ** createIntMatrix(unsigned int rows, unsigned int cols) 
    {

  int ** matrix;
  unsigned int i,j;

  matrix = (int **) calloc(cols, sizeof(int *));

  for(i = 0; i < cols; i++)
    matrix[i] = (int *) calloc(rows, sizeof(int));


  for(i = 0; i < cols; i++)
    for(j = 0; j < rows; j++)
      matrix[i][j] = 0;

  return matrix;
}

我在下面的代码中使用这个函数创建了三个实例,

cout<<"allocating temporary data holders..."<<endl;
  int ** temp_meanR;
  int ** temp_meanG;
  int ** temp_meanB;
  temp_meanR = createIntMatrix(img->height,img->width);
  temp_meanG = createIntMatrix(img->height,img->width);
  temp_meanB = createIntMatrix(img->height,img->width);
cout<<"....done!"<<endl;

我正在访问这些元素,例如 temp_meanB[4][5]

但不幸的是,我在运行时收到以下错误:

allocating temporary data holders...
....done!
tp6(1868) malloc: *** error for object 0x122852e08: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
Abort trap

我哪里错了?

【问题讨论】:

  • 你为什么用 calloc 而不是 new?
  • 如果您使用calloc 分配内存,则无需手动将元素初始化为零。根据cplusplus.com/reference/clibrary/cstdlib/calloc,所有位都自动设置为0。
  • malloc 是 C 方式,在 C++ 中使用 new。

标签: c++ multidimensional-array malloc


【解决方案1】:
  for(i = 0; i < cols; i++)
    for(j = 0; i < rows; i++)
       matrix[i][j] = 0;

注意里面的 for 循环,上面写着 j=0; i&lt;rows; i++在 Aarohi Johal 的编辑之前

接下来,您不必手动将内存设置为 0,因为 calloc 会为您完成。

在 C++ 中,您应该使用 newdelete

在代码段中

matrix = (int **) calloc(cols, sizeof(int *));

for(i = 0; i < cols; i++)
  matrix[i] = (int *) calloc(rows, sizeof(int));

我认为首先应该分配行,然后为每一行链接int 数组。

像这样可视化:

        +--------+
        | matrix |
        +--------+
          |            c  o  l  s
          |     +----------------------------+
          V     |                            |
   +--  +---+   +---+---+---+       +---+
   |    |   |-->|   |   |   | . . . |   |
   |    +---+   +---+---+---+       +---+
   |    |   |--+
 r |    +---+  |   +---+---+---+       +---+
 o |    |   |  +-->|   |   |   | . . . |   |
 w |    +---+      +---+---+---+       +---+
 s .      .
   .      .
   .      .
   |    |   |
   |    +---+   +---+---+---+       +---+
   |    |   |-->|   |   |   | . . . |   |
   +--  +---+   +---+---+---+       +---+

先做行,再做列,在上面的可视化中,arr[i][j] 的解释就像普通数组一样。

【讨论】:

  • 太棒了!谢谢。我修正了代码中 i,j 循环的错字。
  • 还请注意您分配行和列的顺序,关于分配的行列顺序,我是否清楚我在说的图表?在您的代码中,实际上 rows 充当列,cols 充当行。
  • 这正是问题所在。由于您的帖子,我成功编译了:)
猜你喜欢
  • 1970-01-01
  • 2018-03-07
  • 1970-01-01
  • 1970-01-01
  • 2013-05-06
  • 1970-01-01
  • 2020-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多