Always :) that you learn that something "always has to be" has something wrong in learning or in the mechanism because if one has to put something to obtain in result, but one can not put it, it is because in some situation does not need, otherwise you should not be required to use something you have to always use so in any case.
Argument passing by reference
You have to understand why there is a pointer . And that it is used in a function parameter as a way to make it bidirectional, that is, it causes you to send a value to the function, but if it is changed the variable that contained it in the calling function will have its value changed together.
This is what happens with scanf()
. You are passing a variable to the function not because you need to send a value to the function, in fact the variable can not even have a valid value, for scanf()
this does not matter, the point is that at the end of scanf()
the value typed by the user needs to be placed somewhere and it places just the variable you passed as the second argument (the first is the formatting text, and there may be other arguments with more variables).
So for the variable in the calling function to receive the value of scanf()
it must be passed as a reference, ie it must be a pointer to a variable memory region (if you still have questions, understand what a variable ).
You may think, "but why do not you return that value?" Because the function already has a return to something else, something that people do not realize and almost always misuse. Almost every use of scanf()
should be in if
to indicate if the operation was successful, because that is what it returns. You should not use the variable that receives its value without a verification if everything worked out. Read the documentation and see what the return of scanf()
is.
See more in Why use pointers as function parameters .
Why do not you need in the example
Then understand that the most common when you learn to use scanf()
is to do something like this:
int x;
scanf("%d", &x);
This is necessary because you are passing the address of the variable x
to function scanf()
, you are not passing the value of x
. To pass the memory address an operation is required, since the default is to get the value of the variable. This operator is &
.
But there are some cases you do not need. Because? Because the variable is already a pointer. If the parameter of scanf()
expects a pointer and its variable already stores a memory address, you do not have to use &
. A well-known case is:
char texto[11];
scanf("%s", texto);
texto
is already a pointer, no need. Your case is the same, ptr_int
is a pointer, so you do not need to use any operator to get memory address, it is already what you need, even because it has already been used in (strictly speaking, unnecessarily, only if you do this in didactic exercise):
int *ptr_int = &int1;