Nick Nick - 1 month ago 18
C Question

Why does scanf require &?

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


Why does
scanf
need the address of the variable?

Answer

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