Program alters variable value during execution

Viewed 62

I'm writing the following C program. At this stage, the program should take input from the user and store it into the variable days:

#include <stdio.h>
#define SIZE 10

int main(){
    int days = 0;
    int high_temp[SIZE] = {0};
    int low_temp[SIZE] = {0};

    printf("---=== IPC Temperature Calculator V2.0 ===---\n");

    if ((days < 3) || (days > 10)) {

        printf("Please enter the number of days, between 3 and 10, inclusive: %d");
        scanf("%d", &days);

        while ((days < 3) || (days > 10)) {
            printf("\nInvalid entry, please enter a number between 3 and 10, inclusive: ");
            scanf("%d", &days);
            printf("\n");
        }
    }

    for(int i = 1; i < days; i++){
        printf("\nDay %d - High: ", i);
        scanf("%d", &high_temp);

        printf("\nDay %d - High: ", i);
        scanf("%d", &low_temp);
    }

}

However, during execution, the problem assigns an absurd value to days:

---=== IPC Temperature Calculator V2.0 ===---
Please enter the number of days, between 3 and 10, inclusive: 87585440

Mind you that days is initialized as 0 and the value is suppose to change within the if statement.

3 Answers

This statement

printf("Please enter the number of days, between 3 and 10, inclusive: %d");

has undefined behavior. Remove %d from the outputted string.

Just write

printf("Please enter the number of days, between 3 and 10, inclusive: ");

If you want to use the specifier as a prompt then write

printf("Please enter the number of days, between 3 and 10, inclusive: %%d");

that is used %%d.

Your printf() call contains a format specifier of %d but you aren't passing an integer after the format. That's undefined behavior and it's pulling some unknown value from memory.

If you want to print the value of days you need to pass it in the function call. If not then remove the %d specifier.

printf("Please enter the number of days, between 3 and 10, inclusive: %d", days);

here you go, hope that helps

#include <stdio.h>
#define SIZE 10
int main(){
int days = 0;
int high_temp[SIZE] = {0};
int low_temp[SIZE] = {0};

printf("---=== IPC Temperature Calculator V2.0 ===---\n");

if ((days < 3) || (days > 10)) {

    printf("Please enter the number of days, between 3 and 10, inclusive: ");
    scanf("%d", &days);

    while ((days < 3) || (days > 10)) {
        printf("\nInvalid entry, please enter a number between 3 and 10, inclusive: ");
        scanf("%d", &days);
        printf("\n");
    }
}

for(int i = 0; i < days; i++){
    printf("\nDay %d - High: ", (i+1));
    scanf("%d", &high_temp[i]);

    printf("\nDay %d - Low: ", (i+1));
    scanf("%d", &low_temp[i]);
}

for (int i = 0; i < days; i++){

   printf("\n Day # %d", (i + 1));
   printf("\n\t High: %d", high_temp[i]);
   printf("\n\t Low: %d", low_temp[i]); 
}

}

Related