c - scanf读取完全不同的数字

标签 c scanf

这是我在 Visual Studio 中的所有代码:

#include <stdio.h>

int main (void) {

    int input;

    puts("There are 10 seats available on the next flight");
    puts("Where would you like to reserve a seat?");
    puts("Please type 1 for First Class");
    puts("Please type 2 for Economy");

    scanf("%d", &input);

    if (input == 1) {
        printf("You Typed %d\n", &input);
    }
    if (input == 2) {
        printf("You Typed %d\n", &input);
    }

}

但是当我运行该程序时,我得到的输出是:

There are 10 seats available on the next flight
Where would you like to reserve a seat?
Please type 1 for First Class
Please type 2 for Economy
1
You Typed 6159588
Press any key to continue . . .

我每次都会得到一个完全随机的数字。因此,我似乎无法在输入后编写任何内容。为什么会发生这种情况?

最佳答案

你打印出来的是变量input地址,而不是它的值!这是因为 printf 按值接受其参数 - 只是因为它们可以这样传递。因此你需要的是

printf("%d", input); // without the ampersand!

scanf - 相比之下 - 是根本不同的。它将把一个值放入您提供给它的变量中 - 因此需要一个指针。

简单的例子:

int n = 7;

void myPrintf(int v)
{
    ++v;
}

void myScanf(int* v)
{
    ++*v;
}

int main(int argc, char* argv[])
{
    myPrintf(n); // n passed by value, cannot be modified
                 // (but printf does not intend to, either!)
    myScanf(&n); // n will be incremented!
                 // (scanf does modify, thus needs a pointer)
    return 0;
}

不过,回到根源:仍然存在一个基本问题:您正在传递一个指针,但将其计算为 int。如果两者的大小不同(现代 64 位硬件上就是这种情况),那么您就有麻烦了。然后从堆栈中读取不同大小的值,并且地址的一部分实际上被丢弃(指针地址需要 "%p" 格式说明符,确保从堆栈中读取适当数量的字节 - in现代系统 8 vs. 4 int 的情况)。

关于c - scanf读取完全不同的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42932881/

相关文章:

我可以使用 openmp 或 pthreads 通过不同线程调用相同的系统调用吗

C scanf() 问题?

c - fscanf 读入双数组奇怪值

c - scanf 的异常行为

c - 如何从文本文件中读取并存储在c中的矩阵中

c - 我如何读取 C 中的数字?

c - 如何在没有任何非标准库的情况下在 C 中进行多处理

c++ - FFMPEG Seeking 带来音频伪像

c - 当 scanf 输入是字符但转换说明符和变量是整数时,打印整数变量将返回 "weird"数字。为什么?

c - fscanf 只读取第一个字段 C