Printf ("% d") does not display what I entered

My code is:

printf("Enter a number : "); scanf("%d", &number); printf("%d is what I entered\n", &number); 

Enter 2

Expected Result: 2 is what I entered

Actual Output: 2293324 is what I entered

What is the problem?

+7
c printf
source share
6 answers
 printf("%d is what I entered\n", &number); 

incorrect because %d (in printf ) expects an argument of type int , not int* . This calls Undefined Behavior , as shown in the draft (n1570) of the C11 standard (highlight):

7.21.6.1 fprintf function

[...]

  1. If the conversion specification is not valid, the behavior is undefined. 282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined .

Fix it 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 number ( & is the operator address).

So scanf does not need to know the value of number . He needs an address (in this case int* ) to write input to it.

printf , on the other hand, does not require an address. You just need to know the value ( int , in this case) to print. This is why you do not use & in front of a variable name in printf .

+10
source share

You use the & operator on number , which means you take its address, so you do not print the value of number , but its address, you must:

 printf("%d is what I entered\n", number); 
+7
source share

If you used the -Wall -g option of the compiler, you should see an error at compile time:

 # cc -Wall -g ex.c -o ex ex.c: In function 'main': ex.c:9:10: warning: format '%d' expects argument of type 'int', but argument 2 has type 'int *' [-Wformat=] printf("%d is what I entered\n", &number); ^ 
+4
source share
 #include <stdio.h> int main(void) { printf("Enter a number: "); int number; scanf("%d", &number); printf("The number is: %d\n", number); return 0; } 

This should solve your problem.

In scanf() , you first need to specify what the input element will be (int, float, char, char *, etc.) for your example "%d" for integers.

After that, you should receive the address of your product. To do this, you need to use the & operator before the variable.

Your error occurred because you used the & operator on printf() . This basically means that you are printing the address on the stack where you saved the integer. But without & you print the actual value.

Hope this helps.

+2
source share

This & operand sets the address of the variable "number". You should not use it.
Decision:

 printf( "%d is what I entered\n", number); 
+2
source share

u you can try to remove from the number and just write the number

 printf("%d is what I entered\n", number); 

In fact, it indicates and displays the memory location of your input, i.e. 2

0
source share

All Articles