动态2D阵列创建运行时错误

时间:2011-05-18 13:13:31

标签: c++ multidimensional-array malloc

我正在尝试使用以下函数代码创建一个multidimentional 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

我在哪里错了?

1 个答案:

答案 0 :(得分:5)

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

注意里面的for循环,它说j=0; i<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 .      .
   .      .
   .      .
   |    |   |
   |    +---+   +---+---+---+       +---+
   |    |   |-->|   |   |   | . . . |   |
   +--  +---+   +---+---+---+       +---+

首先在上面的可视化中执行行然后是cols,然后arr[i][j]解释就像普通数组一样。