简体   繁体   中英

C: return element of pointer array from function

I'v got question when I practiced section 5.8(page 113) of K & R The C Programming Language.

original source code is here

/* month_name: return name of n-th month */
char *month_name(int n)
{
    static char *name[] = {
        "Illegal month",
        "January", "February", "March",
        "April", "May", "June",
        "July", "August", "September",
        "October", "November", "December"
    };
    return (n < 1 || n > 12) ? name[0] : name[n];
}

And I already know that we can't return local variable's pointer because it's from stack and it will be destroyed(?) after function return. But in this example they use static to remain that variable.

The question is "Why they still work after I delete static notation".

I changed code to

/* month_name: return name of n-th month */
char *month_name(int n)
{
    char *name[] = {
        "Illegal month",
        "January", "February", "March",
        "April", "May", "June",
        "July", "August", "September",
        "October", "November", "December"
    };
    return (n < 1 || n > 12) ? name[0] : name[n];
}

and they still work very well.

BUT. if I return name instead of name[n] , it doesn't work as I expected.

Why does it work?

It still works because the array contains pointers to string literals. String literals have static storage duration even if the array the holds their addresses doesn't.

In fact an optimizing compiler should wise up to the fact, and produce identical code in both cases.

When you return name however, the same rules that you noted apply. So you get undefined behavior. Although unless you change the return type of the function, then returning name shouldn't compile, since char* and char** are incompatible types.

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