简体   繁体   中英

Segmentation fault in a recursive function that operates on char array in C

I'm writing Tic-tac-toe in C and I have problem with function that puts a sign on the gameboard. Here's the code:

int aiPutSign(int difficultyLevel, char board[])
{
    if(difficultyLevel == 1)
    {
        srand(time(NULL));
        int field = rand() % 9;
        return board[field] == ' ' ? field : aiPutSign(difficultyLevel, board);
    } else if(difficultyLevel == 2)
    {
        //to do
        return 2;
    } else if(difficultyLevel == 3)
    {
        //to do
        return 3;
    }
}

Unfortunately, I get segmentation fault error. All I know that there is a problem with recursion and it causes an error but I have no idea how is that happening and how to repair it.

In short: board is 9 characters array that holds nine spaces and I put X and O signs in it after every move of each player. If player (here computer AI) tries to put sign on field that is already filled recursion comes in and rand() generates another number of field.

Do not put srand(time(NULL)); in your aiPutSign function, you'll get the same random number at every call. Call srand once for example at the start of your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM