-1
我是malloc的新手。我在哪裏會出現可怕的錯誤?無法在2D陣列中分配內存
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
typedef enum {RED_WINS, YELLOW_WINS, TIE, STILL_PLAYING} gamestate;
typedef enum {EMPTY, RED_COIN, YELLOW_COIN} square;
typedef struct {
int numRows, numCols;
int coinsInBoard;
gamestate state;
square** squares;
} gameboard;
gameboard* gameboard_create(int numRows, int numCols);
void gameboard_print(const gameboard board);
void gameboard_initialize(gameboard* board);
這是我不知道我在做什麼比在任何地方。
// allocates space for the gameboard and its squares
gameboard* gameboard_create(int numRows, int numCols) {
gameboard* result = malloc(sizeof(gameboard));
result->squares= malloc(sizeof(square*)*numRows);
for(int i = 0; i<numRows; i++){
result-> squares[i] = (square*)malloc(sizeof(square)*numCols);
}
for (int i =0; i< result->numRows; i++){
for(int j= 0; j< result->numCols; j++){
result->squares[i][j] = EMPTY;
}
}
return result;
}
// prints the coins currently in the board
void gameboard_print(const gameboard board){
for (int i = 0; i < board.numRows; i++) {
for (int j = 0; j < board.numCols; j++) {
printf("* ");
}
printf("\n");
}
}
int main() {
printf("test\n");
gameboard* result = gameboard_create(5, 5);
gameboard_print(*result);
return 0;
}
我想分配足夠的內存爲2D陣列,將播放連接4在任何大小的主板上。從「測試」
目前沒有什麼與衆不同的是印刷
(1)究竟是什麼問題?具體說明(2)從'malloc'移除鑄件,因爲它們是多餘的(3)發佈[mcve] –
這部分代碼是可以的。更明確你遇到什麼問題(併發布MCVE) –
謝謝你們。試圖做mcve –