C scanf奇怪的行为

0 c scanf

我在给定的代码中遇到一个问题,即输入(2 X++ X++)会产生输出(2 0),或者任何输入都会产生(n 0)而不是(n n).任何人都可以解释这种行为的原因吗?

#include <stdio.h>

int main()
{
    int n;
    scanf("%d", &n);
    int number = 0;
    for (int i = 0; i < n; i++)
    {
        char operation[3];
        printf("%d\n", n);
        scanf("%s", operation);
        printf("%d\n", n);
        if (operation[0] == '+' || operation[2] == '+')
            number++;
        else
            number--;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Cho*_*ett 5

operation被定义为3个字符长 - 即两个"数据"字符加上空终止符.你读了一个长度为三个"数据"字符的字符串,但是你忘记了空终止符.

也就是说,你的记忆可能是这样的:

+---+---+---+---+
|   |   |   | 2 |
+---+---+---+---+
<-operation-> n
Run Code Online (Sandbox Code Playgroud)

然后用"null"终结符读入"X ++",你的内存读取:

+---+---+---+---+
| X | + | + | \0|
+---+---+---+---+
<-operation-> n
Run Code Online (Sandbox Code Playgroud)

最终'\0'需要在分配的空间中进行说明operation.