【问题标题】:Scanf_s reading wrong inputScanf_s 读取错误的输入
【发布时间】:2017-02-02 04:38:30
【问题描述】:

对于下面的代码(在 C 中)

    int small_a, small_b;
    printf("Please input two numbers\n");
    scanf_s("%d %d", &small_a, &small_b);
    printf("%d %d", &small_a, &small_b);
    int test_2nd = small_a - small_b;
    if (test_2nd < 0) {
        printf("a is smaller %d", &small_a);
    }
    else {
    printf("b is smaller %d", &small_b);

当我写 4 和 2 时它打印的值是一个巨大的六位数字(在这种情况下为 5504620 和 5504608)我不明白哪里出错了。 stdio.h 已包含在标题中。

【问题讨论】:

  • printf("%d %d", &amp;small_a, &amp;small_b); remove &amp; --> printf("%d %d", small_a, small_b);
  • 1) 检查任何scanf() 系列函数的返回值,以确保操作成功。 2)打印变量时,使用printf()传递实际变量,而不是变量的地址。
  • 建议您阅读有关如何提问的“帮助”部分。例如,当问题是关于运行时问题时,就像你的问题一样,发布干净编译、很小但仍然显示问题的代码。

标签: c printf output scanf


【解决方案1】:

这里的问题在于打印语句。在代码中

 printf("%d %d", &small_a, &small_b);

您不需要(想要)获取(打印)地址。删除那个&amp;

也就是说,这实际上调用了undefined behavior%dprintf() 需要 int 类型的参数,而您实际上是在提供 int *,从而导致 UB。

FWIW,要打印地址(指针),您需要使用%p 格式说明符并将参数转换为void *

【讨论】:

  • 魔鬼在细节中吧?我猜它只是在打印地址。
  • @Ansh 当然可以。 上帝在细节中。总是仔细检查。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
  • 2020-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
相关资源
最近更新 更多