scanf函数在C中是如何工作的?
为什么在scanf函数在C中是如何工作的?,c,scanf,C,Scanf,为什么在scanf函数中需要符号(&)。在下面的C代码中,错误的输出或类型(编译或运行时)是什么 #include <stdio.h> void main() { int a; printf("enter integer:"); scanf("%d", a); } #包括 void main(){ INTA; printf(“输入整数:”); scanf(“%d”,a); } 因为scanf需要一个指向值将进入的变量(即引用)的指针。C中的&是一个返回操作
scanf
函数中需要符号(&)。在下面的C代码中,错误的输出或类型(编译或运行时)是什么
#include <stdio.h>
void main() {
int a;
printf("enter integer:");
scanf("%d", a);
}
#包括
void main(){
INTA;
printf(“输入整数:”);
scanf(“%d”,a);
}
因为scanf
需要一个指向值将进入的变量(即引用)的指针。C中的&
是一个返回操作数地址的运算符。这样想,如果您只给scanf
变量a
,而不给&
,它将通过值传递给它,这意味着scanf
将无法设置其值供您查看。通过引用传递它(使用&
实际上传递一个指向a
的指针)允许scanf
对其进行设置,以便调用函数也能看到更改
关于具体的错误,你真的不知道。该行为未定义。有时,它可能会默默地继续运行,而您不知道scanf
更改了程序中的某些值。有时它会导致程序立即崩溃,如本例所示:
#include <stdio.h>
int main()
{
int a;
printf("enter integer: ");
scanf("%d",a);
printf("entered integer: %d\n", a);
return 0;
}
执行显示分段错误:
$ ./test
enter integer: 2
Segmentation fault
如果你问这样的问题,我建议你现在就开始学习“它就是这样”
您将了解到您需要一个与,因为
scanf
接受一个或多个指针参数。如果a是int变量,则它不是指针&a(“a的地址”)是一个指针,因此它将与scanf
一起工作,这是因为在C中,函数参数是通过值传递的。为了让scanf()
函数修改main()函数中的“a
”变量,应将“a
”的地址提供给scanf()
,因此使用了与号(的地址) 您不必总是将&
与scanf
一起使用。你需要做的是传递指针。如果您是C新手,您应该花一些时间阅读comp.lang.C常见问题解答:
具体而言:
void foo(int bar)
{
bar = bar + 1;
}
int main(void)
{
int x = 0;
printf("x before foo = %d\n", x);
foo(x);
printf("x after foo = %d\n", x);
return 0;
}
程序的输出将是
x before foo = 0
x after foo = 0
现在程序的输出是
x before foo = 0
x after foo = 1
还请注意,将数组传递给函数时(例如使用“%s”转换说明符读取字符串时),不需要使用&
运算符;数组表达式将隐式转换为指针类型:
int main(void)
{
char name[20];
...
scanf("%19s", name); // name implicitly converted from "char [20]" to "char *"
...
}
scanf中的“&”仅用于获取变量的地址。通过使用指针,您可以使用不带“&”的
scanf
:
int myInt;
int * pointer_to_int;
pointer_to_int = &myInt;
scanf("%d", pointer_to_int);
一般来说,使用“&”通常比创建指针更容易避免使用“&”。将“&”用作旁注,
main
返回int
,而不是void
。
int main(void)
{
int a, *pa; // declare pa as a pointer to int
...
pa = &a; // assign address of a to pa
scanf("%d", pa); // scanf() will write to a through pa
...
}
int main(void)
{
char name[20];
...
scanf("%19s", name); // name implicitly converted from "char [20]" to "char *"
...
}
int myInt;
int * pointer_to_int;
pointer_to_int = &myInt;
scanf("%d", pointer_to_int);