简体   繁体   English

尝试在C中访问2D数组的地址并出现分段错误

[英]Trying to access address of 2D array in C and getting segmentation fault

I'm a beginner with C, and I'm a little confused about pointers and how they are passed to other functions. 我是C语言的初学者,对指针以及如何将指针传递给其他函数感到有些困惑。 I'm working on a project and in my main function, I malloc a 2D array of chars representing a game board. 我正在开发一个项目,并且在我的主要功能中,我分配了代表游戏板的2D字符数组。

// 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方法时,我正在传递电路板的地址。

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? 作为第二个问题,在分配新的2D阵列之前,是否需要将旧的2D阵列释放()?

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, ie, first * , then [i] . 因为数组下标运算符[]优先级高于间接运算符*优先级,因此将首先执行,但是您需要相反的操作,即首先* ,然后是[i]

First, what you have declared is not a 2-d array , it's a double pointer. 首先,您声明的不是2-d array ,而是双指针。 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. 第二个问题的答案是,是的,您应该先free旧指针,然后再重新分配它,否则程序将发生内存泄漏。 The first value of board will be lost and you will not be able to free it. board的第一个价值将丢失,您将无法释放它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM