如何在C scanf函数功能的工作? [英] How does the scanf function work in C?
问题描述
为什么你需要符号(&安培;)在 scanf函数
功能。将输出或错误(编译或运行时)的类型在下面的C code是什么?
的#include<&stdio.h中GT;无效的主要(){
int类型的;
的printf(请输入整数:);
scanf函数(%d个,一);
}
的&安培;
在C是返回操作数地址的操作。想想这样说,如果你想简单地给 scanf函数
变量 A
没有&放;
,它将被-值,这意味着 scanf函数
将无法将其值设置为你看到传递给它。按引用传递它(使用&安培;
实际上将指针传递到 A
)允许 scanf函数
来设置它,以便调用函数会看到变化了。
对于特定的错误,你真的不能告诉。该行为是不确定的。有时,它可能会默默地继续运行,而不让你知道 scanf函数
在程序的某个地方改变了一些价值。有时它会导致程序在这种情况下立即崩溃,如:
的#include<&stdio.h中GT;
诠释的main()
{
int类型的;
的printf(请输入整数:);
scanf函数(%d个,一);
的printf(进入整型数:%d \\ n,一);
返回0;
}
编译它显示了这一点:
$ gcc的-o测试test.c的
test.c的:在函数'主':
test.c的:6:警告:格式'%D'希望键入'诠释*',但参数2的类型'诠释'
和执行节目分段错误:
$ ./test
输入整数:2
分段故障
Why do you require ampersand (&) in the scanf
function. What will the output or type of error (compile or runtime) be in the following C code?
#include <stdio.h>
void main() {
int a;
printf("enter integer:");
scanf("%d", a);
}
The &
in C is an operator that returns the address of the operand. Think of it this way, if you would simply give scanf
the variable a
without the &
, it will be passed to it by-value, which means scanf
will not be able to set its value for you to see. Passing it by-reference (using &
actually passes a pointer to a
) allows scanf
to set it so that the calling functions will see the change too.
Regarding the specific error, you can't really tell. The behavior is undefined. Sometimes, it might silently continue to run, without you knowing scanf
changed some value somewhere in your program. Sometimes it will cause the program to crash immediately, like in this case:
#include <stdio.h>
int main()
{
int a;
printf("enter integer: ");
scanf("%d",a);
printf("entered integer: %d\n", a);
return 0;
}
Compiling it shows this:
$ gcc -o test test.c
test.c: In function ‘main’:
test.c:6: warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘int’
And executing shows a segmentation fault:
$ ./test
enter integer: 2
Segmentation fault
这篇关于如何在C scanf函数功能的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!