Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

returning a string

returning a string

returning a string


   I have a doubt, in the following program prints the string returned by throwstring()function.

   The string which the function is returning local to the function or outside of the function.

   Can somebody throw light on underlying mechanism..

      char* throwstring();
      printf("%s\n", throwstring());
    char *throwstring()
       return "I'm from throwstring func";


Thanks in Advance

RE: returning a string

Unless the char * in throwstring() is defined as static, you're going to end up with something other than what you want in short order, once the area of memory where the local char * was stored is overwritten.  By declaring a static char * or static char[], the memory is allocated in a different area than with local variables.

If you want to keep the value to work with you should strcpy the return value from a function if the value can change upon subsequent function calls.


RE: returning a string

Your program is presently returning a pointer to a string constant, so there is no problem with disappearing storage.  All string constants are stored in memory which exists for the life of the program.

If you had a true local array, then what trollacious was saying about static would apply.

If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close