How function return value behaves differently for variables and arrays

I have the following case:

char *func1()
{
   char val[]="This is test!";
   return val;
}

      

Now I know what char val[]

is the local array of the function and it will no longer be available as the function returns.

Now why is this wrong for the next case?

char func2()
{
   char val='C';
   return val;
}

      

Tested it

int main()
{
   printf("output1 :: %s \n",func1()); // print garbage characters
   printf("output2 :: %c \n",func2()); // print `C`
   return 0;
}

      

+3


source to share


2 answers


C returns a value. When you write return val;

to func2

, a copy is returned val

. It doesn't matter that the original one is val

destroyed, you still have a copy.



In func1

you will return a copy of the pointer to val

. It is not the same as a copy val

. There func1

are no copies val

. Arrays and pointers are different; and pointers have no identity with what they point to. Once val

destroyed, you can no longer use a pointer to it.

+5


source


The function func2

returns a copy of the variable char val

.



+2


source







All Articles