Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong string when passed to function

Tags:

c

function

I've been trying the "How many days in a given month".

My main looks like this:

int main(void) {
    int numberOfDays, month = 0;
    char* input = (char*) malloc(10);

    printf("Please enter a month (\"1\", \"Jan\", \"January\", \"jan\" or \"january\" etc.):\n> ");
    scanf(" %s", input);
    selectMonth(input);

    switch (month) {
        case 1:
            numberOfDays = 31;  break;
        ...
        default:
            numberOfDays = 0;
            printf("Invalid month.\n");
    }
...

And selectMonth:

int selectMonth(char* input) {
    int month = 0;

    if (!strcasecmp(input, "jan") || !strcasecmp(input, "january") || !strcasecmp(input, "1")) {
        month = 1;
    }
    ...

    return month;
}

When I put the contents of selectMonth inside main, it works fine. But when I have a separate function for the else/ifs and return the month, the switch goes straight to the default case. Why is that?

I'd appreciate any help!

like image 616
jmkjaer Avatar asked Mar 02 '26 01:03

jmkjaer


1 Answers

selectMonth(input);

The expression's result is not being assigned to month... so:

month = selectMonth(input);

Shall help resolve your forementioned issues.

Remember, C has local scope variables, so the month that you declare inside selectMonth is not the same month as the one declared in main(). Thus, the one in main() does never get any value other than zero, which it was initialized with.

like image 129
3442 Avatar answered Mar 03 '26 18:03

3442



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!