Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Scope of character pointer and character array in a function (http://www.go4expert.com/forums/scope-character-pointer-character-array-t29148/)

pawanjoshi 27Sep2012 17:52

Scope of character pointer and character array in a function
 
Hi,

Following are two programs which behave differently for same situtaion.
Code:


#include<stdio.h>
char *somfun()
{
char *t="pawan";
return t;
}
int main()
{
        puts(somfun());
}

Output : pawan
Code:


#include<stdio.h>
char *somfun()
{
char t[]="pawan";
return t;
}
int main()
{
        puts(somfun());
}

output : garbage value

Both variable inside function "somfun" are having local scope even after that first program is printing the value of t...how is it possible???????

xpi0t0s 29Sep2012 13:46

Re: Scope of character pointer and character array in a function
 
Neither is correct, because in both cases t is on the stack and invalid after the function returns.

This is correct, but you must remember to free the memory some time later otherwise this will leak memory:
Code:

char *morefun()
{
  char *t=malloc(6*sizeof(char));
  strcpy(t,"pawan");
  return t;
}



All times are GMT +5.5. The time now is 18:41.