gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:15:17 25 4
gpt4 key购买 nike

为什么在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com