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?