Returning strings from functions

Question:
I would like to write a function that receivesan 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;}

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: