在函数中强制初始化全局变量

时间:2017-05-19 07:48:42

标签: c global-variables

我用c编写一个简单的游戏,但全局变量不起作用 请看下面的代码

全局变量

int board[ROW][COL];
int count[8];
int playerswitch = 1;

int main(void) 
{
    init_board();  //board initialization
    play_tictactoe();
}

play_tictactoe

void play_tictactoe(void) 
{
    int col, row;

    while (1)
    {
        printf("player %d. Enter rows and columns to place stones: ", playerswitch);
        scanf_s("%d %d", &row, &col);

        if (playerswitch == 1)
        {
            if (put_stone(player1, row - 1, col - 1) != TRUE)
            {
                printf("Put again \n");
                continue;
            }
            else
            {
                display_board();
                if (check_win(player1, row - 1, col - 1) == TRUE)
                    break;

                playerswitch = 2;
                continue;
            }
        }
        else if (playerswitch == 2)
        {
            if (put_stone(player2, row - 1, col - 1) != TRUE)
            {
                printf("Put again \n");
                continue;
            }
            else
            {
                display_board();
                if (check_win(player2, row - 1, col - 1) == TRUE)
                    break;

                playerswitch = 1;
                continue;
            }
        }
    }
}

这是个问题 enter image description here

我第一次在全局变量2-D数组中输入一个值时,输出是正确的,但是第二次输入时,全局变量2-D数组被强制初始化,所以我输入的值是丢失。再一次,第二个条目将在第三个条目上正确显示。为什么是这样? 我试过调试,它是通过check_win函数初始化的,但我不知道为什么。

check_win

int check_win(int player, int checkRow, int checkCol)
{
    int check, row, col;
    count[8] =  0;

    row = checkRow;
    col = checkCol;

    while(row>=0 || col>=0)
    {
        if (board[row][col] != player)
                return FALSE;

        count[0]++;
        row--;
        col--;
    }

    row = checkRow;
    col = checkCol;

    while (row < ROW || col < COL)
    {
        if (board[row][col] != player)
            return FALSE;

        count[1]++;
        row++;
        col++;
    }

    for (int i = 0; i < 8; i++)
    {
        if (count[i] == 5)
            return TRUE;
    }
}

0 个答案:

没有答案