这是我在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 %dn", &input);
}
if (input == 2) {
printf("You Typed %dn", &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"
格式说明符,以确保从堆栈中读取适当的字节数 - 在现代系统的情况下,8 与 4 表示 int(。