c - scanf 后变量重置

标签 c linux string gcc scanf

我写了下面的函数:

typedef enum {GREEN,BLACK, WHITE} color;

void StartGame(Piece board[8][8])
{
    color currentPlayer=WHITE;
    char location[2];
    int gameover=1;
    while(gameover)
    {
        printf("%d\n",currentPlayer);

        if(currentPlayer==WHITE)
            printf(BOLDWHITE"White: Please select a piece:\n");
        else
            printf(BOLDBLACK"Black: Please select a piece:\n");

        printf("%d\n",currentPlayer);

        scanf("%s",location);

        printf("%d\n",currentPlayer);
        if(currentPlayer==WHITE)
            currentPlayer=BLACK;
        else
            currentPlayer=WHITE;

    }
} 

我在任何级别上打印 currentPlayer 以查看发生了什么 -> 这里是我得到的:

2
White: Please select a piece:
2
a1
0
2
White: Please select a piece:
2

为什么scanf后当前播放器为0?我没有碰它。

最佳答案

缓冲区 location 只有 2 个字符的空间,scanf 在末尾放置了一个额外的 NUL 字符。因此,您遇到了堆栈损坏问题。只需给 location 留出更多空间,例如:

char location[8];

编辑

因为你只想读取一个字符串,我推荐你使用fgets ,它允许您限制从输入字符串中读取的字符数。因此,我的代码将如下所示:

char location[8];
...
fgets(location, sizeof(location), stdin); //instead of scanf, fgets reads at most one less than buffer's size characters.

您只需要担心 fgets 将最后一个结束行字符 (\n) 放在末尾这一事实,但如果您只需处理字符串的前 2 个字符。

关于c - scanf 后变量重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25249738/

相关文章:

c - 位掩码左移

c++ - 为文件写入实现互斥锁

c - 在 OpenCV 中读取 AVI 文件时出现未知错误

linux - 变量 While 循环

string - 在 Excel VBA 项目中匹配相似但不完全相同的文本字符串

Python textwrap 和忽略部分字符串

c - 时差为零秒

linux - GCC 在不同的优化级别上以不同方式处理 float 比较

java des cipher在windows上的不同结果

string - 评估字符串中的 boolean 表达式 - Go