【发布时间】:2017-02-23 01:00:13
【问题描述】:
我是 C 的初学者,我对指针以及它们如何传递给其他函数有点困惑。我正在做一个项目,在我的主要功能中,我 malloc 一个代表游戏板的 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));
}
稍后可以调用一个函数来加载游戏的保存版本,从而重新分配我的棋盘变量。
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));
}
}
当我在 main 函数中调用 stringToGame 方法时,我传递了棋盘的地址。
stringToGame(&board, &rows, &cols, &turn, &winLength);
传递板的地址会导致分段错误,我不知道为什么。
作为第二个问题,我是否需要在 malloc 新数组之前为电路板释放()我的旧二维数组?
【问题讨论】:
-
如果你有一个专门的函数来分配/重新分配板子,它会让你的代码更容易管理。
-
@M.M 这就是我的计划,只要我可以让它工作!
标签: c pointers multidimensional-array memory-address