[英]Trying to access address of 2D array in C and getting segmentation fault
我是C語言的初學者,對指針以及如何將指針傳遞給其他函數感到有些困惑。 我正在開發一個項目,並且在我的主要功能中,我分配了代表游戲板的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));
}
}
當我在主函數中調用stringToGame方法時,我正在傳遞電路板的地址。
stringToGame(&board, &rows, &cols, &turn, &winLength);
通過板的地址會導致分段錯誤,我不知道為什么。
作為第二個問題,在分配新的2D陣列之前,是否需要將舊的2D陣列釋放()?
這個
*board[i] = malloc(*cols * sizeof(char));
應該
(*board)[i] = malloc(*cols * sizeof(char));
因為數組下標運算符[]
優先級高於間接運算符*
優先級,因此將首先執行,但是您需要相反的操作,即首先*
,然后是[i]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.