C 中的异常 scanf 行为

Anomalous scanf behaviour in C

我正在尝试 运行 C:

中的以下代码
#include <stdio.h>
#include <stdint.h>

void main(){
    int firstNum = 5;
    int16_t secondNum;
    
    printf("Please enter the first number: ");
    scanf("%d", &firstNum);
    printf("Please enter the second number: ");
    scanf("%d", &secondNum);
    
    printf("%d %d\n", firstNum, secondNum);
}

我得到的输出如下:

Please enter the first number: 13
Please enter the second number: 4
0 4

--------------------------------
Process exited after 1.877 seconds with return value 4
Press any key to continue . . .

为什么会这样?

我的 IDE 是 Dev-C++。编译器是 TDM-GCC 4.9.2 64 位版本。程序名称是 TestBit.c(如果相关?)。

注意:当我将行 int16_t secondNum; 更改为 int secondNum; 时,程序按预期运行。

int16_t 与 int 不是一回事;因此通过 scanf 传递一个指针并假装它是一个 int 指针可能会产生意想不到的行为;因此你的问题。

将 int16_t 替换为 int,您的程序就可以运行了。后续阅读类型的 C 编程语言规范及其含义。

尝试更改为:scanf("%hd", &secondNum);

%d是一个4字节的数据说明符,int16_t实际上只有2个字节。

更多参考资料:https://docs.microsoft.com/en-us/cpp/c-runtime-library/format-specification-syntax-printf-and-wprintf-functions?view=vs-2019

int16_t secondNum 的正确说明符来自 <inttypes.h>

// scanf("%d", &secondNum);
scanf("%" SCNd16, &secondNum);

更好的代码会检查 return 值。

if (scanf("%" SCNd16, &secondNum) == 1) {
  Success();
}