c - printf("%d") doesn't display what I input -
my code:
printf("enter number : "); scanf("%d", &number); printf("%d entered\n", &number); i input 2,
expected output : 2 entered
actual output : 2293324 entered
what's problem here?
printf("%d entered\n", &number); is wrong because %d(in printf) expects argument of type int, not int*. invokes undefined behavior seen in draft (n1570) of c11 standard (emphasis mine):
7.21.6.1 fprintf function
[...]
- if conversion specification invalid, behavior undefined. 282) if argument not correct type corresponding conversion specification, behavior undefined.
fix using
printf("%d entered\n", number); then, why scanf require & before variable name?
keep in mind when use number, pass value of variable number , when use &number, pass address of number(& address-of operator).
so, scanf not need know value of number. needs address of (an int* in case) in order write input it.
printf, on other hand, not require address. needs know value (int, in case) printed. why don't use & before variable name in printf.
Comments
Post a Comment