我正在尝试了解从控制台获取输入的不同方法的优点和缺点。我很困惑scanf
。为什么我需要使用use&favNumber
代替favNumber
?
我明白那个&favNumber
是地址位置favNumber
,但是为什么要这样做呢?
我觉得这里有一个类型不匹配的地方favNumber
是一个 int 我告诉scanf
它是一个指向 int 的指针。我以为我把注意力集中在指针上,但这让我有点困惑。任何帮助,将不胜感激。谢谢!
#include <stdio.h>
int main()
{
char userPrompt[100] = "What is your favorite number?";
int favNumber;
printf("%s", userPrompt);
scanf("%d", &favNumber);
printf("%d", favNumber);
return 0;
}
当您按值调用函数时,该函数会获取参数的副本。对函数中参数的任何更改都不会影响原始变量的值。
void foo(int i )
{
i = 20; // The change is local to the function.
}
void bar()
{
int i = 10;
foo(i);
printf("i=%d\n", i); // i is still 10.
}
如果希望函数改变变量的值,函数必须使用指针类型,并且调用函数在调用函数时必须使用变量的地址。
void foo(int* i )
{
*i = 20; // The change is visible in the calling function
}
void bar()
{
int i = 10;
foo(&i);
printf("i=%d\n", i); // i is now 20.
}
这就是为什么scanf
需要指针,并且调用函数在调用时必须使用变量的地址scanf
. scanf
必须能够设置变量的值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)