I have following case:
char *func1()
{
char val[]="This is test!";
return val;
}
Now here i know that char val[] is local array to the function and it will not longer available as function returns.
Now why this not true for following case?
char func2()
{
char val='C';
return val;
}
Have tested it
int main()
{
printf("output1 :: %s \n",func1()); // print garbage characters
printf("output2 :: %c \n",func2()); // print `C`
return 0;
}
C returns by value. When you write return val; in func2, a copy of val is returned. It does not matter that the original val is destroyed, you still have the copy.
In func1 you return a copy of a pointer to val. This is not the same as a copy of val. There are no copies of val in func1. Arrays and pointers are different; and pointers do not have any identity with the thing they point to. Once val is destroyed, you can no longer use a pointer to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With