Omitting the Address-Of Operator When Calling scanf

Don't forget to put the address-of operator in front of arguments when using the scanf library function (the scanf function accesses keyboard input; for more information, see topic ):

main()

{

int val;

printf( "Type a number: " );

scanf( "%d", val ); /* Error! */

printf( "%d", val );

}

When the program calls scanf, it omits the address-of operator that should precede the second argument:

scanf( "%d", val ); /* Error! */

The scanf function expects to be passed a pointer to a variable (in this case, a pointer to val) so it can assign an input value to the variable. But because the address-of operator is missing, the program passes the value of val, not its address.

Instead of storing an input value in val as intended, scanf uses the uninitialized value of val as a pointer and assigns the input value to an unpredictable address. As a result, val remains uninitialized and the program overwrites memory elsewhere—two very undesirable events.

Here is the correct way to call scanf in this program:

scanf( "%d", &val );