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

mor*_*lir 0 c++ malloc multidimensional-array

我正在尝试使用以下函数代码创建一个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;
}
Run Code Online (Sandbox Code Playgroud)

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

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;
Run Code Online (Sandbox Code Playgroud)

我正在访问这些元素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
Run Code Online (Sandbox Code Playgroud)

我在哪里错了?

pho*_*xis 5

  for(i = 0; i < cols; i++)
    for(j = 0; i < rows; i++)
       matrix[i][j] = 0;
Run Code Online (Sandbox Code Playgroud)

注意里面的循环,它说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));
Run Code Online (Sandbox Code Playgroud)

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

可见这样:

        +--------+
        | matrix |
        +--------+
          |            c  o  l  s
          |     +----------------------------+
          V     |                            |
   +--  +---+   +---+---+---+       +---+
   |    |   |-->|   |   |   | . . . |   |
   |    +---+   +---+---+---+       +---+
   |    |   |--+
 r |    +---+  |   +---+---+---+       +---+
 o |    |   |  +-->|   |   |   | . . . |   |
 w |    +---+      +---+---+---+       +---+
 s .      .
   .      .
   .      .
   |    |   |
   |    +---+   +---+---+---+       +---+
   |    |   |-->|   |   |   | . . . |   |
   +--  +---+   +---+---+---+       +---+
Run Code Online (Sandbox Code Playgroud)

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