以下是我在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 . . .
我每次都得到一个完全随机的数字。因此,在输入工作之后我似乎无法得到任何东西。为什么会这样?
答案 0 :(得分:1)
您打印出来的是变量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 vs .4 for int)。