开发者

Dynamic 2D Array Creation Runtime Error

I'm trying to create a multidimentional int array with the following function code:

int ** createI开发者_如何学JAVAntMatrix(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;
}

I create three instances using this function in the following code,

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;

I'm accessing these elements like temp_meanB[4][5].

But unfortunately, I get the following error during runtime:

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

Where am I going wrong here?


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

note the inside for loop, it says j=0; i<rows; i++ (before Aarohi Johal's edit)

Next you do not have to set the memory manually to 0, as calloc does it for you.

In C++, you should use new and delete .

In the code segment

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

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

I think first the rows should be allocated and then for each row link the int arrays.

Visulize like this:

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

First do the rows and then the cols, in the above visualization, then the arr[i][j] interpretation would be like normal array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜