c - scanf 函数在 C 中如何工作?

标签 c scanf

为什么在 scanf 函数中需要和号 (&)。以下 C 代码的输出或错误类型(编译或运行时)是什么?

#include <stdio.h>

void main() {
    int a;
    printf("enter integer:");
    scanf("%d", a);
}

最佳答案

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;
}

编译显示:

$ 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’

并且执行显示段错误:

$ ./test 
enter integer: 2
Segmentation fault

关于c - scanf 函数在 C 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2062648/

相关文章:

在 C/C++ 中将字符串转换为不同的数据类型

c - 如何在C中不使用递归来反向打印树路径?

c - 为什么进程不能抢占中断?

c - %d 长整型

c - 在 C 中使用 scanf 进行解析

c++ - 关闭cin与C scanf同步的弊端

c - 如果使用管道时子进程数大于处理器数,进程是否会被阻塞?

c++ - 为什么 scanf 似乎跳过了输入?

c - 如何在c中显示printf语句的行号?

c - sscanf 解析格式化字符串