我正在寫一個簡單的棋盤遊戲。當程序第一次運行時,我想要做的事情是打印空白的紙板,然後詢問用戶X
和Y
座標,然後在他輸入的座標中打印帶有玩家令牌的紙板。當我運行該程序將打印空板,然後問我對X
座標,然後Y
協調,那麼它給了我下面的錯誤:無法在遊戲板中打印令牌
X: 1, Y: 2
Y: 2, Y: 3
Segmentation fault (core dumped)
什麼讓這個錯誤,我如何修復它?謝謝
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdbool.h>
struct p1Data{
int xCoordinate;
int yCoordinate;
bool flag;
};
char **gameBoard;
int height, width, boardArea, xCor, yCor, dataSize, i;
char **allocateMemory(int boardHeight, int boardWidth);
void fillBoard(char **board, int height, int width, struct p1Data data[], int sizeData);
void printBoard(char **board, int boardHeight, int boardWidth);
void freeBoardArray(char **board, int boardHeight);
int main(int argc, char** argv){
height = 4;
width = 4;
boardArea = height * width;
struct p1Data data[boardArea];
dataSize = sizeof(data)/sizeof(data[0]);
data[0].flag = false;
gameBoard = allocateMemory(height, width);
fillBoard(gameBoard, height, width, data, dataSize);
printBoard(gameBoard, height, width);
printf("\n");
for(i = 0; i < boardArea; i++){
printf("Enter X-Coordinate: ");
scanf("%d", &xCor);
printf("Enter Y-Coordinate: ");
scanf("%d", &yCor);
data[i].flag = true;
data[i].xCoordinate = xCor;
data[i].yCoordinate = yCor;
fillBoard(gameBoard, height, width, data, dataSize);
printBoard(gameBoard, height, width);
printf("\n");
}
return 0;
}
char **allocateMemory(int boardHeight, int boardWidth){
int i;
char **gameBoard;
gameBoard = (char **)malloc(sizeof(char *)*boardHeight);
for(i = 0; i < boardWidth; i++){
gameBoard[i] = (char *)malloc(sizeof(char)*boardWidth);
}
return gameBoard;
}
void fillBoard(char** board, int height, int width, struct p1Data data[], int sizeData){
int i, j, x, y;
for(i = 0; i < height; i++){
for(j = 0; j < width; j++){
board[i][j] = '.';
}
}
if(data[0].flag == true){
for(i = 0; i < sizeData; i++){
x = data[i].xCoordinate;
y = data[i].yCoordinate;
board[x][y] = 'O';
printf("X: %d, Y: %d\n", x, y);
}
}
}
void printBoard(char **board, int boardHeight, int boardWidth){
int i, j;
printf("/");
for(i = 0; i < boardWidth; i++){
printf("-");
}
printf("\\");
printf("\n");
for(i = 0; i < boardHeight; i++){
printf("|");
for(j = 0; j < boardWidth; j++){
printf("%c", board[i][j]);
}
printf("|");
printf("\n");
}
printf("\\");
for(i = 0; i < boardWidth; i++){
printf("-");
}
printf("/");
}
void freeBoardArray(char **board, int boardHeight){
int i;
for(i = 0; i < boardHeight; i++)
free(board[i]);
free(board);
}
編譯時,始終啓用所有警告,然後修復這些警告。發佈的代碼會導致編譯器輸出多個警告。 (對於'gcc',至少使用:'-Wall -Wextra -pedantic'我也使用:'-Wconversion -std = gnu99')爲了讓你開始,參數:'argc'和'argv'不是用過的。所以代碼應該爲main使用以下簽名:'int main(void)' – user3629249