2017-07-17 2 views
1

zu EXC_BAD_ACCESS Während ein Brett für das Spiel des Lebens zu initialisieren versucht, erhalte ich eine Fehlermeldung:malloc 2D-Array führt

EXC_BAD_ACCESS (code=1, address=0x200000000) 

auf Linie 9 (Ich habe es in einem Kommentar markiert). Ich benutze malloc, um Speicher zu einem 2D-Array, eine Platine voller struct cell s zuweisen. Die Methode, die ich bei StackOverflow gefunden habe. Mache ich etwas falsch? Es gibt auch eine Warnung, bevor ich das Programm in Zeile 6 ausführe:

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

Konnte das etwas damit zu tun haben? Hier ist der Code:

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

Danke, getan. Löst dieses Problem jedoch nicht. – Sahand

+0

Was ist los mit einem VLA? –

Antwort

3

[] ist höhere Ordnung von precedence als *

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

Swap Index um

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

Es gibt andere Bedenken mit dem Code: keine Zuordnungsprüfung, keine Fehlerrückgabe, schwache Variablennamen, Zeigerart Problem mit 'struct cell * const firstrow = * board + nrows;', Ausrichtungsproblem hatte 'struct cell' war ein Basistyp , Verwendung von VLA, Reihenfolge von 'nrows * ncols * sizeof (** board)', dennoch sollte das obige den OP-Code voranbringen. – chux

+0

Vielen Dank! Ich bin 2 Wochen in C zu lernen, also versuche ich einfach, dies zu arbeiten, bevor ich anfange, über das Schreiben von gutem Code nachzudenken. – Sahand