I'm a beginner with C, and I'm a little confused about pointers and how they are passed to other functions. I'm working on a project and in my main function, I malloc a 2D array of chars representing a game board.
// In main, allocate 2D array
char **board = malloc(rows * sizeof(char*));
for (int i = 0; i < rows; i++) {
board[i] = malloc(cols * sizeof(char));
}
A function can be called later which will load a saved version of the game, and thus re-malloc my board variable.
void stringToGame(char ***board, int *rows, int *cols, int *turn, int *winLength) {
// Set new values for rows and cols based on file
...
// Malloc board
*board = malloc(*rows * sizeof(char*));
for (int i = 0; i < *rows; i++) {
*board[i] = malloc(*cols * sizeof(char));
}
}
When I call the stringToGame method in my main function, I'm passing the address of the board.
stringToGame(&board, &rows, &cols, &turn, &winLength);
Passing the board's address is causing a segmentation fault and I have no idea why.
As a secondary question, do I need to free() my old 2D array for the board before I malloc a new one?