I thought the return value of both of the functions would be undefined since they are returning data that is out of scope.
Both functions return a pointer. What matters is the scope of the referent.
In function1
, the referent is the string literal "Hello, World!"
, which has static storage duration. string
is a local variable which points to that string, and conceptually, a copy of that pointer is returned (in practice, the compiler will avoid unnecessarily copying the value).
In function2
, conceptually the referent is the local array string
, which has been automatically sized (at compile time) to be big enough to hold the string literal (including a null terminator, of course), and been initialized with a copy of the string. The function would return a pointer to that array, except that the array has automatic storage duration and thus no longer exists after exiting the function (it is indeed "out of scope", in more familiar terminology). Since this is undefined behaviour, the compiler may in practice do all sorts of things.
Does that mean that all char*
are static?
Again, you need to distinguish between the pointer and the referent. Pointers point at data; they don't themselves "contain" the data.
You have reached a point where you should properly study what arrays and pointers actually are in C - unfortunately, it's a bit of a mess. The best reference I can offer offhand is this, in Q&A format.