2017-07-17 8 views
1

につながり、私はエラーを取得:9行目でmallocの2D配列がEXC_BAD_ACCESS

EXC_BAD_ACCESS (code=1, address=0x200000000) 

(私はコメントでそれをマークしました)。私はを使用して、メモリを2次元配列に割り当てます。ボードは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

おかげで、スワップインデックス順

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

*よりprecedenceの高い順です。しかし、この問題は解決しません。 – Sahand

+0

VLAの何が問題なのですか? –

答えて

3

[]が行わ

 // *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