Why does scanf require &?

2019-01-11 14:14发布

问题:

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?

回答1:

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


回答2:

C function parameters are always "pass-by-value", which means that the function scanf only sees a copy of the current value of whatever you specify as the argument expression.

In this case &i is a pointer value that refers to the variable i. scanf can use this to modify i. If you passed i, then it would only see an uninitialized value, which (a) is UB, (b) is not sufficient information for scanf to know how to modify i.



回答3:

It's not needed.

char s[1234];

scanf("%s", s); 

Works just fine without a single & anywhere. What scanf and company need are pointers. To let it modify a particular variable, you pass the address of that variable. For a few types that happens by default. For others, you use & to take the address (get a pointer to that variable).



回答4:

Because otherwise it would only be altering a copy rather than the original.



回答5:

scanf requires the addressOf operator (&) because it takes a pointer as an argument. Therefore in order to pass in a variable to be set to a passed in value you have to make a pointer out of the variable so that it can be changed.

The reason a pointer must be passed to scanf is that if you just passed a variable, you wouldn't be able to directly alter the variable within scanf, so you couldnt set it to the value read in by scanf.

Hope this helps.



回答6:

scanf() stores values, so it needs a place to store them.
This is done by providing the addresses (in pointers) of where to store the values using addressof or &(ampersand) operator.



回答7:

sscanf does not require &

int decimal;
int *pointer = &decimal;
scanf("%d", pointer);

above code is valid



标签: c scanf