Scope of character pointer and character array in a function

pawanjoshi's Avatar, Join Date: Sep 2012
Newbie Member
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???????

Last edited by shabbir; 27Sep2012 at 17:55.. Reason: Code blocks
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
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;
}