我正在尝试编写一个程序,以字母abcd ...作为坐标系,以'U's为图块打印出一块木板。当我使用动态分配的2D数组时,它可以正常工作。现在,我将其更改为静态数组,该程序将打印出乱码(所有行应与第一行相同)。 我知道除了printRow或printBoard函数之外,所有功能都可以正常工作。
我已经意识到的是,根据木板的大小,我得到的行数会有所不同(4印1、6印2、8印3等)
代码如下:
#include <stdlib.h>
#include <stdbool.h>
//Prints a row of the board given the row number
void printRow(int n, int row, char board[][26]) {
int column;
for (column = 0; column < n; column++) {
printf("%c", board[row][column]);
}
}
//Prints the whole board, including the coordinate system
void printBoard (char board[][26], int n) {
//Print top letters
int character = 97, letter;
printf(" ");
for (letter = 0; letter < n; letter++) {
printf("%c", character + letter);
}
printf("\n");
//Reinitialize to print side letters
int row = 0;
for (letter = 0; letter < n; letter++, row++) {
printf("%c ", character + letter);
printRow(n, row, board);
printf("\n");
}
}
bool positionInBounds(int n, int row, int col) {
//Checks to see if letters are greater than max letter or less than a
if (row - 97 >= n || col - 97 >= n || row - 97 < 0 || col - 97 < 0) {
return false;
}
else {
return true;
}
}
void boardConfig(char board[][26], int n) {
printf("Enter board configuration: \n");
char input[20];
int check = 1;
while (check == 1) {
gets(input);
if (input[0] == '!' && input[1] == '!' && input[2] == '!') {
check = 0;
}
if (positionInBounds(n, input[1], input[2])) {
board[input[1]-97][input[2]-97] = input[0];
}
}
}
/*bool checkLegalInDIrection(char board[][26], int n, int row, int col, char colour, int deltaRow, int deltaCol) {
}
*/
int main(void)
{
int n;
printf("Enter the board dimension: ");
scanf("%d", &n);
//Dynamically allocate array and initialize all board positions to default 'U'
/*char **board = (char **)malloc(sizeof(char *) * n);
for (int row = 0; row < n; row++) {
board[row] = (char*)malloc(sizeof(char) * n);
}
*/
char board[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
board[i][j] = 'U';
}
//Set board to default starting positions
board[n/2-1][n/2-1] = 'W';
board[n/2-1][n/2] = 'B';
board[n/2][n/2-1] = 'B';
board[n/2][n/2] = 'W';
}
boardConfig(board, n);
printBoard(board, n);
return 0;
}
这是 current output for an 8 x 8 board:
编辑:我意识到动态数组会更容易使用(这是我最初所做的),但这是一项分配,我们明确要求使用静态数组。我将开发板设置为最多26列,因为最多26个字母。无论实际板子的大小如何,我们都必须创建一个接受board [] [26]的函数。它必须看起来像this。