Why does scanf require &?

I want to read the number from stdin. I do not understand why scanf requires the use of & in front of my variable name:

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

Why scanf need a variable address?

+6
source share
7 answers

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

Here is a super simple example:

 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; } 
+12
source
Function Parameters

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

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

+6
source

Because otherwise it will only be a change of copy, not the original.

+3
source

It's not needed.

 char s[1234]; scanf("%s", s); 

Works great, without one & anywhere. What scanf and company need are pointers. So that it can modify a specific variable, you pass the address of that variable. For several types that occur by default. For others, you use & to accept the address (get a pointer to this variable).

+3
source

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

The reason the pointer should be passed to scanf is because if you just passed the variable, you cannot directly modify the variable in scanf, so you cannot set it to the value read with scanf.

Hope this helps.

+2
source

scanf() stores values, so storage is required.
This is done by providing addresses (in pointers) where to store values ​​using the addressof or & operator (ampersand).

+2
source

sscanf does not require &

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

the code is above

0
source

Source: https://habr.com/ru/post/915769/


All Articles