0

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?

2 Answers2

1

This

*board[i] = malloc(*cols * sizeof(char));

should be

(*board)[i] = malloc(*cols * sizeof(char));

because the array subscript operator [] has higher precedence than the indirection operator * and hence will execute first but you need the opposite to happen, i.e, first *, then [i].

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
0

First, what you have declared is not a 2-d array, it's a double pointer. There is a difference between these two.

Second, you don't need to pass the address of the array to the function, since arrays are passed by reference anyways. You can simply pass a double-pointer to your function after malloc-ing it.

stringToGame(board, &rows, &cols, &turn, &winLength);

And the answer to your secondary question, yes, you should free your old pointer first, before you malloc it again, otherwise your program will have a memory leak. The first value of board will be lost and you will not be able to free it.

Community
  • 1
  • 1
Jarvis
  • 8,494
  • 3
  • 27
  • 58
  • 1
    The `stringToGame` function reallocates the board, so passing `board` by value would not work – M.M Feb 23 '17 at 01:30