I'm making a little minigame with the use of a 2D array. I tried making a function that starts you off with a clean board and want it in such a way that the cleanboard function is an rvalue if that makes sense.
#include <stdio.h>
#include <stdlib.h>
#define MAX 8
#define EMPTY 0
#define BLACK 1
#define WHITE -1
//Fills the 2D array with 0s and places the 4 starting pieces in the middle
int **cleanboard(void){
int newboard[MAX][MAX];
(*newboard)[MAX] = malloc(sizeof*newboard*MAX);
for(int row=0; row<MAX; row++){
for(int col=0; col<MAX; col++){
newboard[row][col] = EMPTY;
}
}
newboard[3][3] = WHITE, newboard[4][4] = WHITE;
newboard[4][3] = BLACK, newboard[3][4] = BLACK;
return newboard;
}
//Displays the board
void printboard(int arr[][MAX]){
printf(" 1 2 3 4 5 6 7 8\n"); //Top numbers
for(int i=0; i<MAX; i++){
for(int j=0; j<MAX; j++){
if(j==0){printf("%d ", i+1);} //Side numbers
switch(arr[i][j]){ //Print piece
case 0: printf(" .");
break;
case 1: printf(" b");
break;
case -1: printf(" w");
break;
}
}
printf("\n");
}
}
int main(){
int **board;
board = cleanboard();
printboard(board);
return 0;
}
With the given code, it outputs:
1 2 3 4 5 6 7 8
1
However, this example is how the board should look:
//Example 2D array:
int grid[MAX][MAX] = {{-1, 1, -1, 1, 0, -1, 1, 0},
{1, -1, -1, 1, 0, -1, -1, 1},
{1, 1, -1, 1, -1, 1, 1, 1},
{-1, 0, -1, -1, -1, 1, 1, -1},
{1, -1, 0, 1, 0, 1, 0, 0},
{0, 1, -1, 1, -1, -1, 1, -1},
{1, 1, 1, -1, 0, -1, -1, -1},
{0, -1, -1, -1, -1, 1, -1, 0}};
printboard(grid);
Output:
1 2 3 4 5 6 7 8
1 w b w b . w b .
2 b w w b . w w b
3 b b w b w b b b
4 w . w w w b b w
5 b w . b . b . .
6 . b w b w w b w
7 b b b w . w w w
8 . w w w w b w .
The cleanboard function isn't storing the values or something which causes the printboard function to stop. Any help is appreciated.
The parameter type for printboard
is what you want. However, the conversion of arrays to pointers only occurs with the first dimension of a multi-dimensional array. You're attempting to convert between a int (*)[MAX]
and a int **
which are not the same thing.
In cleanboard
, you need to define newboard
as:
int (*newboard)[MAX] = malloc(sizeof*newboard*MAX);
Then the function itself should be defined as:
int (*cleanboard(void))[MAX] {
And board
in main
should be defined as:
int (*board)[MAX];
Also, you'll want to print a newline in printboard
after the inner loop runs.