【发布时间】:2016-08-23 04:26:51
【问题描述】:
我正在编写一个简单的棋盘游戏。我想在程序运行时首先打印空棋盘,然后向用户询问X 和Y 坐标,然后在他输入的坐标中打印带有玩家令牌的棋盘。当我运行程序时,它会打印空板,然后询问我X 坐标,然后是Y 坐标,然后它给了我以下错误:
X:1,Y:2
Y:2,Y:3
分段错误(核心转储)
是什么导致了这个错误,我该如何解决?谢谢你
#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 )