I thought the return value of both functions would be undefined, as they return data that goes beyond the scope.
Both functions return a pointer. The scope of the referent is important.
In function1 referent is the string literal "Hello, World!" which has a static storage duration. string is a local variable that points to this string, and conceptually a copy of this pointer is returned (in practice, the compiler avoids unnecessarily copying the value).
In function2 conceptual referent is the local string array, which was automatically set (at compile time) to be large enough to contain a string literal (including the null terminator, of course), and was initialized with a copy of the string. The function will return a pointer to this array, except that the array has an automatic storage duration and, therefore, no longer exists after exiting the function (it really "goes beyond", in the more familiar terminology). Since this behavior is undefined, the compiler can do all kinds of things in practice .
Does this mean that all char* are static?
Again, you need to distinguish between pointer and referent. Pointers indicate data; they themselves do not "contain" data.
You have reached the point where you must correctly examine which arrays and pointers are actually in C - unfortunately this is a bit of a mess. The best recommendation I can offer is this , in Q & A format.
Karl Knechtel Sep 08 '17 at 6:02 2017-09-08 06:02
source share