0

我是 C 的初学者,我正在尝试创建一个井字游戏来练习我最近学到的一些东西。但是,当我尝试将多维数组传递给函数时,游戏就开始出现问题。这是代码:

//Declaring the function to print out the game board

int printGameBoard(int gameBoard[3][3]) ;


int main(int argc, const char * argv[])
{

//declare a multidimentional array to be used as the game board

int *gameBoard[3][3] ;


// set all array values to 0

for (int r = 0; r < 3; r++) {
    for (int c = 0 ; c < 3; c++) {
        gameBoard[r][c] = 0 ;

    }
}

//bool variable to determine whether the game loop should run

bool gameOn = true ;


//variables used to hold the X(C = Column) and Y(R = Row) values of each players guess

int playOneGuessR, playOneGuessC ;
int playTwoGuessR, playTwoGuessC ;

//Call the function to print the game board with all values initialized to 0 i.e.:
//  [ 0 0 0 ]
//  [ 0 0 0 ]
//  [ 0 0 0 ]

printGameBoard(gameBoard) ;

//Begin game loop    

while (gameOn == true) {

//Player 1 enters the Y(Row) value of their guess

    printf("\nPlayer 1: \nPlease Enter The Row Number:\n") ;
    scanf("%d", &playOneGuessR) ;

// Player 1 enters the X(Column) value of their guess        

    printf("Please Enter The Column Number:\n") ;
    scanf("%d", &playOneGuessC) ;

 //Based on players 1's guess, the appropriate array value is assigned to 1 (to denote player 1)

    gameBoard[playOneGuessR][playOneGuessC] = 1 ;


//The function to print the game board is called again to reflect the newly assigned value of 1 

    printGameBoard(gameBoard) ;


   return 0;
 }

}

//The function to print the game board
int printGameBoard(int gameBoard[][3]) {  //THIS IS WHERE IT GOES WRONG.

for (int r = 0; r < 3; r++) {

printf("Row %d [ ", r+1) ;

for (int c = 0; c < 3; c++) {
    printf("%d ", gameBoard[r][c]) ;
}

printf("] \n") ;
}
return 0 ;
}

长话短说:这一直很好,直到我决定将打印游戏板的代码放入一个单独的函数中。我假设我只是错误地传递了数组。

例如,这是一次尝试的输出:

Welcome to tic tac to! 
Here is the game board: 

Row 1 [ 0 0 0 ] 
Row 2 [ 0 0 0 ] 
Row 3 [ 0 0 0 ] 

Player 1: 
Please Enter The Row Number:
1
Please Enter The Column Number:
1
Row 1 [ 0 0 0 ] 
Row 2 [ 0 0 0 ] 
Row 3 [ 0 0 1 ] 

Program ended with exit code: 0 

显然 1 是在错误的地方。它应该在 gameBoard[1,1],也就是中间。有任何想法吗?谢谢!

4

1 回答 1

2

在你的整个程序中你应该使用二维数组

你声明的方式是错误的。

int *gameBoard[3][3] ;  

你需要声明

int gameBoard[3][3] ;  

playOneGuessR在分配和的检查值之前playOneGuessC

if( (playOneGuessR >=0 && playOneGuessR < 3) && (playOneGuessC >= 0  && playOneGuessC < 3) ) 
gameBoard[playOneGuessR][playOneGuessC] = 1 ;  

越界访问数组有多危险?

看到这个编程范式

于 2013-10-19T19:24:43.257 回答