Browse DevX
Sign up for e-mail newsletters from DevX

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



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Returning strings from functions

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?

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.



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