The reason to use that &
is to get a pointer. scanf
always needs pointers, because it's going to use it to give you a value back. But &
is not the only way to get a pointer.
If you have a single int
, char
, long
, float
, or double
variable, you will need to use a &
to get a pointer of it to pass to scanf
:
int i;
scanf("%d", &i);
char c;
scanf(" %c", &c);
long l;
scanf("%ld", &l);
float f;
scanf("%f", &f);
double d;
scanf("%lf", &d);
If you are reading a string, however, you usually do not need an &
:
char str1[10];
scanf("%9s", str1);
char *str2 = malloc(20);
scanf("%19s", str2);
The reason you do not need a &
in either of these cases is that you already have a pointer, although a full explanation of this fact will require more words than I suspect I'll have time for in this answer.
This ends up being one of the reasons why scanf
is a terribly problematic function. scanf
is most useful during your first few weeks as a C programmer, when you have a lot of different things to learn, and scanf
seems like an easy way to get user-entered values in to your program for it to work on. But you can't really understand how to call scanf
without understanding pointers, and pointers aren't something you're going to want to learn about until later.
So at first, a reasonable set of rules for successful scanf
use is:
if your format is |
you should: |
%d , %f , %lf |
use an & |
%c |
use an & , and also use an extra space: " %c" |
%s |
not use an & |
See also this answer.