const char *fun1()
{
const char *a = "hello";
return a;
}
const char *fun2()
{
const char a[] = "hello";
return a;
}
int main(int argc, char *argv[])
{
printf("%s\n", fun1());
printf("%s\n", fun2());
return 0;
}
Output:
cpp:12:12: warning: address of local variable 'a' returned [-Wreturn-local-addr]
12 | return a;
| ^
passwords.cpp:11:16: note: declared here
11 | const char a[] = "hello";
| ^
hello
(null)
What's difference between these two method of a assigning a string? I am getting a warning for one while not the other one? I know local variables get destroyed when we return from a function but why this is not the case with fun1()? Does it get memory somewhere else instead of stack?