【发布时间】:2021-11-01 23:25:06
【问题描述】:
我正在尝试制作井字游戏,并且我正在使用一种单独的方法,该方法会在每回合后更新棋盘。但是,我似乎无法访问在main() 中初始化的二维数组board。
我已经尝试将其公开,就像在 Java 中一样,但它似乎不起作用。
任何帮助将不胜感激。
#include <stdio.h>
#include <stdlib.h>
#define public
#define static
#define private static
int main(void) {
public char board[5][8] = { " | | ", "--+--+--", " | | ", "--+--+--", " | | " };
int turn = 0;
public static int base = 0;
for (size_t row = 0; row < sizeof(board) / sizeof(board[0]); row++) {
for (size_t col = 0; col < sizeof(board[0]) / sizeof(board[0][0]); col++)
printf("%c", board[row][col]);
printf("\n");
}
printf("Player1's turn\n ");
fflush(stdout);
scanf("%i", &turn);
updateBoard(&turn);
}
void updateBoard(int a){
switch (a) {
case 1:
board[0][0] = 'X';
break;
case 2:
board[0][4] = 'X';
break;
case 3:
board[0][6] = 'X';
break;
case 4:
board[2][0] = 'X';
break;
case 5:
board[2][4] = 'X';
break;
case 6:
board[2][6] = 'X';
break;
case 7:
board[4][0] = 'X';
break;
case 8:
board[4][4] = 'X';
break;
case 9:
board[4][6] = 'X';
break;
default:
printf("Please input a correct value (1-9)");
}
for (size_t row = 0; row < sizeof(board) / sizeof(board[0]); row++) {
for (size_t col = 0; col < sizeof(board[0]) / sizeof(board[0][0]); col++)
printf("%c", board[row][col]);
printf("\n");
}
base = 1;
}
【问题讨论】:
-
发送板作为函数 updateBoard 的参数。
-
或者在主函数之外“全局”声明它。
-
#define private static似乎很糟糕。static在 c 中有多种含义。如果它位于函数范围之外的声明中,则它可以表示“仅此翻译单元(例如 *.c 文件)的范围”,而在函数范围内则表示(简化)“保留此变量的值重复调用此函数。”同样通过#define static,您可能会在不知情的情况下破坏很多东西,例如,如果头文件的任何地方都包含static。