This
char str[] = "hello";
is a declaration of a local array that is initialized by the string literal "hello"
.
In fact it is the same as if you declared the array the following way
char str[] = { 'h', 'e', 'l', 'l', 'o', '\0' };
That is the own area of memory (with the automatic storage duration) of the array is initialized by a string literal.
After exiting the function the array will not be alive.
That is the function
char *f2() {
char str[] = "hello";
return str;
}
tries to return a pointer to the first element of the local character array str
that has the automatic storage duration.
As for this function definition
char *f1() { return "hello"; }
then the function returns a pointer to the first character of the string literal "hello"
that indeed has the static storage duration.
You may imagine the first function definition the following way
char literal[] = "hello";
char *f1() { return literal; }
Now compare where the arrays are defined in the first function definition and in the second function definition.
In the first function definition the array literal
is defined globally while in the second function definition the array str
is defined locally.
if the str points to the actual string literal (which has static
duration), why do I get an error?
str
is not a pointer. It is a named extent of memory that was initialized by a string literal. That is the array has the type char[6]
.
In the return statement
return str;
the array is implicitly converted to pointer to its first element of the type char *
.
Functions in C and C++ may not return arrays. In C++ functions may return references to arrays.