2017-07-17 60 views
1

試圖初始化董事會生命的遊戲,我得到一個錯誤:malloc的二維數組導致EXC_BAD_ACCESS

EXC_BAD_ACCESS (code=1, address=0x200000000) 

第9行(我在評論其標記)。我正在使用malloc將內存分配給2D陣列,這是一塊充滿struct cell的板子。我在StackOverflow上找到的方法。難道我做錯了什麼?另外,在我運行第6行發生的程序之前有一個警告:

Incompatible pointer types initializing 'struct cell *const' with an expression of type 'struct cell **'; dereference with * 

這可能與它有關嗎?下面的代碼:

void init_board(int nrows, int ncols, struct cell ***board){ 

    //allocate memory for a 2D array 
    *board = malloc(nrows * sizeof(*board) + nrows * ncols * sizeof(**board)); 

    //Now set the address of each row 
    struct cell * const firstrow = *board + nrows; 
    for(int i = 0; i < nrows; i++) 
    { 
     *board[i] = firstrow + i * ncols; //EXC_BAD_ACCESS... 
    } 

    for(int i = 0; i < nrows; i++){ //fill the entire board with pieces 
     for(int j = 0; j < ncols; j++){ 
      *board[j][i] = new_cell(i, j, 0); 
     } 
    } 
} 
+0

謝謝,完成。雖然沒有解決這個問題。 – Sahand

+0

VLA有什麼問題? –

回答

3

[]precedence順序高於*

// *board[i] = firstrow + i * ncols; //EXC_BAD_ACCESS... 
    (*board)[i] = firstrow + i * ncols; //EXC_BAD_ACCESS... 

交換索引順序

 // *board[j][i] = new_cell(i, j, 0); 
     (*board)[i][j] = new_cell(i, j, 0); 
+1

還有其他一些關於代碼的問題:沒有分配檢查,沒有錯誤返回,弱變量名,指針類型問題與'struct cell * const firstrow = * board + nrows;',對齊問題有'struct cell'是一個基本類型,VLA的使用,'nrows * ncols * sizeof(** board)'的順序,但是上面應該提前OP的代碼。 – chux

+0

非常感謝,它確實!我在學習C的2周時間,所以我試圖在開始考慮編寫好的代碼之前簡單地使用它。 – Sahand