試圖初始化董事會生命的遊戲,我得到一個錯誤: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);
}
}
}
謝謝,完成。雖然沒有解決這個問題。 – Sahand
VLA有什麼問題? –