My code:
printf("Enter a number : ");
scanf("%d", &number);
printf("%d is what I entered\n", &number);
I input 2
,
Expected output : 2 is what I entered
Actual output : 2293324 is what I entered
What's the problem here?
printf("%d is what I entered\n", &number);
is wrong because %d
(in the printf
) expects an argument of type int
, not int*
. This invokes Undefined Behavior as seen in the draft (n1570) of the C11 standard (emphasis mine):
7.21.6.1 The fprintf function
[...]
- If a conversion specification is invalid, the behavior is undefined. 282)If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
Fix it by using
printf("%d is what I entered\n", number);
Then, Why does scanf
require &
before the variable name?
Keep in mind that when you use number
, you pass the value of the variable number
and when you use &number
, you pass the address of number
(&
is the address-of operator).
So, scanf
does not need to know the value of number
. It needs the address of it (an int*
in this case) in order to write the input into it.
printf
, on the other hand, does not require the address. It just needs to know the value (int
, in this case) to be printed. This is why you don't use &
before the variable name in printf
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With