我在移动9 x 9井字游戏程序时遇到问题。
当我输入坐标(5,5)时,x将正确显示在网格上。
我的问题是当我输入其中有数字7的坐标,例如(4,7)时,网格上会显示两个X。
我以前做过程序,将我的数组声明为全局变量。一切都很好。当我切换到动态分配的数组并使用双指针传递该数组时,问题就开始了。所以我猜我的问题是因为我的数组。有人可以告诉我这个问题在哪里发生以及如何解决。
我已经在主数组中声明了数组
//previously the array was declared here
//char grid[ROW][COLUMN];
int main()
{
//dynamically create an array of pointers os size ROW
char **grid = (char **)malloc(ROW * sizeof(char *));
// dynamically allocate memory of size ROW*COLUMN and let *grid point to it
*grid = (char *)malloc(sizeof(char) * ROW * COLUMN);
make move方法
int make_move(char **grid, int x, int y,int row, int col, char letter)
{
if (x < 0 || x >= row || y < 0 || y >= col || grid[x][y] != ' ' )
{
// checks to see if the input is valid
return 1;
}
if( grid[x][y] == ' ')
grid[x][y] = letter;
// sets the coordinates in the grid to the letter
return 0;
}
更新网格方法
// Updates the grid accordingly every time a move is made
void update_grid(char **grid,int x, int y, int row, int col)
{
// int counter = 1;
//checks the input
while (x < 0 || x >= row || y < 0 || y >= col || grid[x][y] != ' ')
{
fputs("Error, Move not valid! Please reenter: ", stderr);
scanf("%d,%d", &x, &y);
}
++counter;
{
//Acts as an increment for the turns of the players
if(counter % 2 == 0)
{
//checks to see if it is player X's turn
grid[x][y] = 'X';
}
if(counter % 2 != 0)
{
//checks to see if it is player O's turn
grid[x][y] = 'O';
}
//prints grid
printf(" ");
for (int c = 0; c < col; c++)
{
printf(" ");
printf(" %d", c);
}
printf("\n");
for (int r = 0; r < row; ++r)
{
printf("%d", r);
printf("|");
for (int dot = 0; dot < (col*row); ++dot)
{
printf("|");
printf("%c", grid[r][dot]);
printf(" ");
if (dot == col - 1)
{
// stops j from over printing
printf("|| \n");
break;
}
}
}
}
}
//dynamically create an array of pointers os size ROW
char **grid = malloc(ROW * sizeof(char *));
for(size_t i = 0; i < ROW; i++){
grid[i] = malloc(COLUMN);
}
您分配了ROW
指针,但只填充了第一个指针,需要给它们每个COLUMN
字节数据。