When you call scanf
with the %d
conversion specifier, the corresponding argument needs to be an expression that evaluates to the location of an integer object into which scanf
will write the input value:
scanf( "%d", location-expression );
location-expression
can take on multiple forms. To read into a single scalar object like x
, you could use the expression &x
.
scanf( "%d", &x ); // &x evaluates to the location of x
Or, you could use a pointer variable that's initialized to point to x
:
int *p = &x; // p stores the address of x
scanf( "%d", p ); // scanf writes to x *through* p; p == &x
The expression p
is equivalent to the expression &x
in this case. We don't use the &
operator on p
, because we want write to the address stored in p
, not the address of p
.
When you write
scanf( "%d", x );
you're telling scanf
to store input to the address stored in x
. There are several problems with that:
x
is not explicitly initialized to anything; its value is indeterminate;
- Because of 1, the odds that
x
contains a value that corresponds to a valid pointer value (that is, the location of an object in your program) are extremely low;
- The type of the expression
x
is int
, but %d
expects its corresponding argument to have type int *
- any modern compiler should yell at you.