I'm trying to write a program which prints out a board with the letters abcd... as a coordinate system and with 'U's as the tiles. When I used a dynamically allocated 2D array it worked fine. Now that I've changed it to a static array, the program prints out gibberish (all the rows should be the same as the first one). I know all functions are working properly except the printRow or printBoard functions.
Something I've realized is that, depending on the size of the board, I get a different number of rows (4 prints 1, 6 prints 2, 8 prints 3, etc)
Here is the code:
#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;
}
This is the current output for an 8 x 8 board:
Edit: I realize a dynamic array would be easier to use (that's what I did initially) but this is an assignment and we are explicitly asked to use a static array.I set the board to have a maximum of 26 columns because there are a maximum of 26 letters. We must create a function that takes in board[][26] regardless of the size of the actual board. It must look like this.