Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf("%d") doesn't display what I input

Tags:

c

printf

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?

like image 454
Steven Elcarim Avatar asked Aug 16 '15 14:08

Steven Elcarim


1 Answers

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

[...]

  1. 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.

like image 57
Spikatrix Avatar answered Oct 02 '22 12:10

Spikatrix