1 2 3 4 5
|
const char* printday(int i) // 1 prints Sunday, 2 prints Monday,...
{
char* dayname[7]= {"Sunday", "Monday","Tuesday","Wednesday", "Thursday", "Friday", "Saturday"};
return dayname[i];
}
|
What is the "dayname"?
It is an array of seven
pointers.
What are the "Sunday", "Monday","Tuesday","Wednesday", "Thursday", "Friday", "Saturday"?
They are constant string literals. Not pointers, not variable, not in stack, nor in the heap.
What does the array initialization do?
It does store the addresses of the literal constants into the arrays.
What does the function return?
A copy of the address of one constant string literal.
That is not an address of a local variable.
Yes, the dayname is in the stack and yes, it is gone after the function returns. The names, however, are not in the dayname nor in the stack.
char dayname[7][100]= {"Sunday", "Monday","Tuesday","Wednesday", "Thursday", "Friday", "Saturday"};
That is different. The array does not contain seven pointers. It has seven character arrays.
The names are still literal constants, it is not their address that is stored in the dayname.
The content of literals, the characters are
copied into the arrays.
That dayname has characters in stack. That function returns address to stack that goes poof on return.