Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Dec 4, 1998

Returning strings from functions

Question:
I would like to write a function that receives an integer and converts this into a string representing the integers value in binary. At the moment I am struggling to get the function to return a string. Do I have to get the function to return a pointer to the string? If so how is this declared and called?

Answer:
If you are using C++, you would probably want to return a pointer to some sort of String object. Assuming you are just using C then, yes, you would want to return a pointer to that string.

The only tricky part is due to the fact that variables declared within your function are destroyed when your function returns. Some ways of handling this include allocating memory from the system, which requires that the caller free that memory when it is done, or allocate the string data outside of your function so it is not destroyed when the function returns.

Perhaps the simplest approach is to simply declare a local string as static so that it is not destroyed.

char *GetString()
{
   static char s[80];
   strcpy(s, "Here is a string!");
   return s;
}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date