你的代码中有一堆错误。请参阅内联注释。
//Use all capitals for defines
#define BOARD_SIZE 8
//Just reset the whole array to spaces.. No need to traverse byte by byte.
void resetBoard(char* board) {
//memset version
//memset(board, ' ', (BOARD_SIZE*BOARD_SIZE)*sizeof(char));
//non memset version
for (int i=0; i<(BOARD_SIZE*BOARD_SIZE); i++) *board++='x';
}
void printBoard(char *board) {
for (int i = 0; i < BOARD_SIZE; i++){
for (int j = 0; j < BOARD_SIZE; j++){
//Access the 2D array like this (y * width of array + x)
printf("%c", board[i*BOARD_SIZE+j]);
printf(" ");
}
printf("\n");
}
}
//Don't start a name using capitals.. Later when you program c++ or similar you will understand :-)
int main()
{
//This is a more dynamic memory model and is not allocated on the stack.. (free when done!!)
char *board=(char*)malloc(BOARD_SIZE*BOARD_SIZE);
//there are several ways of working with arrays.. No need to complicate stuff if not needed.
//Just point out the first byte of the array.. (See the methods takes a char pointer and that is what's passed the methods)
if (board) {
resetBoard(board);
//Test to see if it works
board[1*BOARD_SIZE+2]='0';
printBoard(board);
free(board);
} else {
printf("Out of memory!\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
或者像 2020 年一样炫耀它!
#define B 16 //Define the size of the 2d matrix
void printMatrix(char*b){for(int i=-1;i<B*B-1;(++i+1)%B?printf("%c ",b[i%B*B+i/B]):printf("%c\n",b[i%B*B+i/B])){}} //Print the 2d matrix
int main(){
char b[B*B]={[0 ...B*B-1]='x'}; //Reserve the 2d matrix space and set all entries to 'x'
printMatrix(&b[0]); //pass the pointer to the print 2d matrix method
return 0; //Done!
}
或 2021 ;-) (二维数组)
#define B 32
void p(char b[B][B]){for(int i=-1;i<B*B-1;(++i+1)%B?printf("%c ",b[i%B][i/B]):printf("%c\n",b[i%B][i/B])){}}
int main(){
char b[B][B]={[0 ...B-1][0 ...B-1]='x'};
p(&b[0]);
}