1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Scope of character pointer and character array in a function

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

  1. pawanjoshi

    pawanjoshi New 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 a moderator: Sep 27, 2012
  2. xpi0t0s

    xpi0t0s 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;
    }
    
     

Share This Page