Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

returning a string

Status
Not open for further replies.

gplkrsna

Programmer
Sep 13, 2007
1
US
Hi,

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..


************************************************
main()
{
char* throwstring();
printf("%s\n", throwstring());
}

char *throwstring()
{
return "I'm from throwstring func";
}

**************************************************


Thanks in Advance
 
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.

Lee
 
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.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top