Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How return value of function behave differently for variable and array

Tags:

c

function

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;
}
like image 990
Random Avatar asked Jun 28 '26 16:06

Random


1 Answers

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.

like image 185
M.M Avatar answered Jul 01 '26 05:07

M.M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!