I have the code below. The problem is with variable r
, which first holds a random number between 1-10. Later it is compared inside a loop to a user input number. The loop ends when the user guesses the randomly generated number.
I am using short
type for the guess, and int
for the randomly generated number r
. The point is that after the first guess of the user, r
becomes 0 and I don't know why. This problem does not happen if guess
is an int
.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
srand(time(NULL));
int r = (rand()%10)+1;
short guess = -1;
printf("%d\n", r);
while ((guess)!= r){
printf("%d\n", (int) guess);
printf("%d\n", guess);
printf("%d\n", r);
printf("Give me a number from 1 to 10: ");
scanf("%d",&guess);
if (guess> r){
printf("The number is lower\n");
}
else if (guess<r){
printf("The number is higher\n");
}
else {
printf("Corrent!\n");
}
}
return 0;
}
An output example would be:
7
-1
-1
7
Give me a number from 1 to 10: 5
The number is lower
5
5
0
Give me a number from 1 to 10:
The problem is here:
scanf("%d",&guess);
The variable guess
is a short
, but the %d
format specifier to scanf
expect a pointer to an int
. Using the wrong format specifer to printf
or scanf
invokes undefined behavior .
What most likely happened is that an int
on your system is larger than a short
, resulting in writing to bytes in memory past where guess
resides, overwriting nearby variables, in this case r
. This behavior however is not guaranteed and could change with seemingly unrelated code changes.
Either use the correct format specifier:
scanf("%hd",&guess);
Or change the type of guess
to int
. Since there's no real reason to use a short
here, I'd recommend the latter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.