using function getting the address of string into a pointer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • geeta719
    New Member
    • Mar 2010
    • 10

    using function getting the address of string into a pointer

    char * get();
    void main()
    {
    char*c;
    c=get();
    printf("%s",c);
    }
    char * get()
    {
    char ch[3]="km";
    return(ch);
    }

    the string is not getting dereferenced by the pointer 'c',
    i.e the function is not returning the address of string
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    The function is returning the address of the string. Unfortunately since the string has automatic storage scope as soon as the function returns it is destroyed so the pointer returned is invalid.

    Comment

    • geeta719
      New Member
      • Mar 2010
      • 10

      #3
      so how can i can get the string from a function as such???

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        Well you have 3 options in C basically
        1. Return a pointer to static data. However this is not re-entrant or thread safe and is generally considered a bad idea.
        2. Return a pointer to data that has been malloc'd, but then you need to be sure to free the returned pointer once you have finished with it or you get a memory leak. The potential for memory leaks makes this not a brilliant idea either but it is sometimes useful.
        3. Don't return a pointer, instead pass in a pointer to a location to store the result in from the external program along with a number indicating the size of the passed in buffer. Return a boolean (0 or 1) value indicating if the supplied buffer was large enough or an integer indicating the required size of the buffer if it was not large enough.

        Comment

        Working...