简体   繁体   中英

Using uninitialized memory

I'm learning C and I have one problem right now.

This is my part of code for a guessing number game, it's simple:

int secretNumber = 13;
int guess;

while (guess != secretNumber) {
    printf("Enter a number: ");
    scanf("%d", &guess);
}
printf("Win!");

And I receive the following errors:

  • Using uninitialized memory
  • uninitialized locar variable 'guess' used.
  • return value ignored 'scanf'.

Your problem is because the guess is uninitialized and you are comparing it in the while loop in the beginning.

In this case, it is better to construct it using in the do {} while() form. This way, the comparison is done after you got the value for the guess variable:

int secretNumber = 13;
int guess;

do {

    printf("Enter a number: ");
    scanf("%d", &guess);
} while (guess != secretNumber);

printf("Win!");

You are going to have some warning in the scanf() as well because you are not checking the return value.

To fix that as well, you can check like this:

if (scanf("%d", &guess) != 1) {
    print("invalid input, try again\n");
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM