如何在C scanf函数功能的工作? [英] How does the scanf function work in C?

查看:120
本文介绍了如何在C scanf函数功能的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么你需要符号(&安培;)在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆