Unable to get the guessing number of the game to work in C

I tried writing a C program to say the number of times you guessed the right number.

#include <stdio.h> #include <stdlib.h> int main() { int i, searchNumber, Number, rightGuess; rightGuess = 0; printf("Give your number: "); scanf("%d",&searchNumber); printf("\n\n Give 10 numbers: "); for(i=1;i<=9;i++){ scanf("%d \n",&Number); if(Number == searchNumber){ rightGuess++; } } printf("You guessed the number %d times",&rightGuess); return 0; } 

However, every time I run it, it says that I guessed number 6356736 times. Although I only entered the number 0 times. Any help?

+5
source share
2 answers

Your printf call should be

printf("You guessed the number %d times", rightGuess);

i.e. do not pass a pointer to rightGuess according to the format specifier %d . Currently, the behavior of the program is undefined! (It may well display the address of rightGuess , which takes into account a large number, but does not rely on it, you need to use %p to output the addresses of pointers.)

+5
source

You may have made a mistake in printf() .

If there is a variable called var , &var means the memory address where var is located. Perhaps the number 6356736 that you saw in your program is the memory address, not the value in the var variable.

You will need to change this line to print the value of the rightGuess variable

 printf("You guessed the number %d times", &rightGuess); 

To this line.

 printf("You guessed the number %d times", rightGuess); 
+7
source

Source: https://habr.com/ru/post/1257734/


All Articles