1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Scope of character pointer and character array in a function

Discussion in 'C' started by pawanjoshi, Sep 27, 2012.

  1. pawanjoshi

    pawanjoshi New Member

    Joined:
    Sep 26, 2012
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Software Engineer
    Location:
    Noida
    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 a moderator: Sep 27, 2012
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    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;
    }
    
     

Share This Page