0

私は C の初心者で、最近学んだことを練習するために Tic Tac To ゲームを作成しようとしています。ただし、多次元配列を関数に渡そうとするとすぐに、ゲームに問題が発生し始めました。コードは次のとおりです。

//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 ;
}

簡単に言うと、ゲームボードを印刷するコードを別の関数に入れることにするまで、これはうまくいきました。配列を間違って渡しているだけだと思います。

たとえば、ここに 1 回の試行の出力があります。

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

プログラム全体で、2次元配列を使用することになっています

宣言の仕方が間違っています。

int *gameBoard[3][3] ;  

宣言する必要があります

int gameBoard[3][3] ;  

とのチェック値を割り当てる前playOneGuessRplayOneGuessC

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

範囲外の配列にアクセスするのはどれほど危険ですか?

このプログラミングパラダイムを参照してください

于 2013-10-19T19:24:43.257 に答える