为什么 scanf 需要 &? [英] Why does scanf require &?

查看:75
本文介绍了为什么 scanf 需要 &?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从标准输入中读取一个数字.我不明白为什么 scanf 需要在我的变量名称之前使用 &:

I want to read a number from stdin. I don't understand why scanf requires the use of & before the name of my variable:

int i;
scanf("%d", &i);

为什么scanf需要变量的地址?

Why does scanf need the address of the variable?

推荐答案

需要更改变量.由于 C 中的所有参数都是按值传递的,如果您希望函数能够更改参数,则需要传递一个指针.

It needs to change the variable. Since all arguments in C are passed by value you need to pass a pointer if you want a function to be able to change a parameter.

这是一个非常简单的例子:

Here's a super-simple example showing it:

void nochange(int var) {
    // Here, var is a copy of the original number. &var != &value
    var = 1337;
}
void change(int *var) {
    // Here, var is a pointer to the original number. var == &value
    // Writing to `*var` modifies the variable the pointer points to
    *var = 1337;
}
int main() {
    int value = 42;
    nochange(value);
    change(&value);
    return 0;
}

这篇关于为什么 scanf 需要 &?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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