2011-05-18 85 views
0

我試圖創建一個具有以下功能的代碼多維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 

我要去哪裏錯了嗎?

+3

爲什麼你使用calloc而不是新的? – Gal 2011-05-18 13:17:02

+1

如果使用'calloc'分配內存,則不需要手動將元素初始化爲零。根據http://www.cplusplus.com/reference/clibrary/cstdlib/calloc/所有位自動設置爲0。 – 2011-05-18 13:18:50

+1

malloc是C的方式,在C++中使用新的。 – snoofkin 2011-05-18 13:23:04

回答

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

注意在for循環中,它說(前Aarohi的Johal的編輯j=0; i<rows; i++

接下來,您不必手動設置內存爲0,因爲calloc會爲你。

在C++中,應該使用newdelete

在代碼段

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

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

我覺得第一行應分配,然後爲每行鏈接int陣列。

Visulize這樣的:

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

首先做的行,然後將COLS,在上述可視化,則arr[i][j]解釋將像正常陣列。

+0

輝煌!謝謝。我在代碼中修正了i,j循環的錯字。 – 2011-05-18 15:04:03

+0

還注意到您分配行和列的順序,我是否清楚說明了我所說的關於分配的行列順序?在你的代碼中,實際上'rows'充當列,'cols'充當行。 – phoxis 2011-05-18 16:24:27

+0

那正是錯誤的地方。我編譯成功,因爲你的帖子:) – 2011-05-18 17:16:41