Archived

This topic is now archived and is closed to further replies.

G a m e D e v

return a string

Recommended Posts

Is there a way in C/C++ to have a function return a string. Does it involve an array of functions returning a char? Please give me a code example. Thanks
"Beware of computer programmers that carry screw drivers"

Share this post


Link to post
Share on other sites
Oh. My. God!

Sigh...

If you wish to return a C string (char *), specify that as your return type like so:

(char *) ReturnAString( ... )
{
char * a_string;
// make sure you intialize your string here
return a_string;
}

For robustness you could check the string''s validity within the function, as follows:

(char *) ReturnAString( ... )
{
char * a_string;
// make sure you intialize your string here
if( a_string == NULL )
return NULL;
return a_string;
}

That way the calling function can ascertain whether the string returned was valid before using it.

If you want to return an STL string, you can either place your function within the std namsepace or prefix all string functions with std::.

// namespace version
using namespace std;
string ReturnAString( ... )
{
string stl_string;
// initialize string. optionally verify string
return stl_string;
}

// non-namespace version
std::string ReturnSTDString( ... )
{
std::string std_string;
// initialize string. optionally verify string
return std_string;
}

Share this post


Link to post
Share on other sites
Usually, it's a better idea to use pointers rather than return a string.
IE: (needed to make a couple fixes)

    
void func1(){
char* mystring;
mystring = (char*)malloc(sizeof(char)*strlen("Hello World\0");
strcpy(mystring,"Hello");
printf("%s",mystring); //prints "Hello"

func2(&mystring);
printf("%s",mystring); //prints "Hello World"

free(mystring);
}

void func2(char** mystring){
strcat((*mystring)," World");
}


Edited by - Nytegard on July 1, 2001 8:54:35 PM

Share this post


Link to post
Share on other sites
quote:
Original post by Oluseyi
For robustness you could check the string's validity within the function, as follows:

    
<snip>
if( a_string == NULL )
return NULL;
return a_string;
<snip>



That's clearly redundant. The next time you say "Oh. My. God! Sigh..." to a legitimate question from a beginner, try not to make yourself look even more clueless.

Nytegard: I was going to mention that you forgot malloc, but I see that you added it. The only other issue with your example is that there's no need for func2 to require a char**, since it doesn't need to change the value of the mystring pointer. No big deal, but it might confuse someone who's just getting started with C.

Update: Just noticed two more nit-picky things in Nytegard's example. The malloc line needs another ')' at the end, and strlen won't count the '\0' in your string, even if you explicitly include and extra one in the quotes. The correct line should read:
  
mystring = (char*)malloc(sizeof(char)*(strlen("Hello World") + 1));



Edited by - EvilTwin on July 1, 2001 9:40:22 PM

Share this post


Link to post
Share on other sites
quote:
Original post by EvilTwin
That''s clearly redundant. The next time you say "Oh. My. God! Sigh..." to a legitimate question from a beginner, try not to make yourself look even more clueless.



Touchy. What if the string is "mis-initialized" by some other function? What if the string is never intialized? Are we guaranteed its value will always be NULL in those scenarios? The point is to validate the string; I merely provided a simplistic (and largely redundant) check. Feel free to replace it with more elaborate schemes to ensure the string is usable for your pruposes.

The "Oh. My. God! Sigh...", btw, is a reference to the abundance of individuals without a programming foundation that are seeking to make games. Should this be? Shouldn''t the basics of programming be learned first (return types clearly falls within the basics). It is by no means an attempt to insult the beginner, though some may construe it as such. If you so interpreted it, I apologize for my lack of clarity.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by Oluseyi
Touchy. What if the string is "mis-initialized" by some other function? What if the string is never intialized? Are we guaranteed its value will always be NULL in those scenarios? The point is to validate the string; I merely provided a simplistic (and largely redundant) check. Feel free to replace it with more elaborate schemes to ensure the string is usable for your pruposes.


Ok, sorry about the "clueless" jab, but the extra if statement really doesn''t do anything. If a_string is NULL, then "return a_string;" will return NULL. There''s no reason at all to explicitly check if it''s NULL and explicitly return NULL if it is. Maybe you meant to have additional code in between like this:
  (char *) ReturnAString()
{
char * a_string;

a_string = (char*)malloc(SOMETHING_BIG_ENOUGH);
if( a_string == NULL )
return NULL;

sprintf(a_string, "So''s you wanna string, eh buddy?\n");

return a_string; // Don''t forget to free it when you''re done!

}


Now the if statement makes sense, because it prevents a possible crash in sprintf.

quote:
The "Oh. My. God! Sigh...", btw, is a reference to the abundance of individuals without a programming foundation that are seeking to make games. Should this be? Shouldn''t the basics of programming be learned first (return types clearly falls within the basics). It is by no means an attempt to insult the beginner, though some may construe it as such. If you so interpreted it, I apologize for my lack of clarity.


Yeah, it can be annoying to see people constantly thinking that the job of a game programmer is easier than it is, but I still think we''re better off pointing them down the right path than saying things like that. It''s no big deal if I construe it as an insult, but if the beginner does then maybe he''ll just blindly stumble down the wrong path instead of asking for help. Anyway, sorry about my harsh response earlier.

Share this post


Link to post
Share on other sites
quote:
Original post by Anonymous Poster
Ok, sorry about the "clueless" jab, but the extra if statement really doesn''t do anything. If a_string is NULL, then "return a_string;" will return NULL. There''s no reason at all to explicitly check if it''s NULL and explicitly return NULL if it is. Maybe you meant to have additional code in between like this:




Actually I did. That''s why I had the commented line that says "initialize string". But it''s okay, no offence taken.

quote:
Yeah, it can be annoying to see people constantly thinking that the job of a game programmer is easier than it is, but I still think we''re better off pointing them down the right path than saying things like that. It''s no big deal if I construe it as an insult, but if the beginner does then maybe he''ll just blindly stumble down the wrong path instead of asking for help. Anyway, sorry about my harsh response earlier.



Well, it''s amazing what a cool reply can do to alleviate the situation and promote understanding. If there were more people like that then we''d have virtually no flame wars. I''ll be more careful next time.

Share this post


Link to post
Share on other sites
What does ''(char *)'' and ''char*'' mean? In my knowlage those arent pointers. What are they? Are they pointers? Sorry about my ignorance.



"Beware of computer programmers that carry screw drivers"

Share this post


Link to post
Share on other sites
char, as you know, is the single byte character type. The indirection operator (*) used in this context creates a pointer to memory. Used in conjunction, (char *) or char* create a pointer to a char in memory. A string in C is just a series of chars, and since their memory is allocated in linear fashion they can be referred to by a pinter to the start of that memory. Consider:

char * c;
// this is the same as (char *) c; the parentheses just make
// things neater sometimes

*c refers to the object/memory pointed to.
c refers to the actual pointer, so if you initialized your pointer like so:

// initialize an array of chars, ie a string
c = (char *)malloc(sizeof(char) * n);

you can manipulate the contents of the string itself like this:

// THIS CAUSES YOU TO LOSE YOUR MEMORY, WHICH WILL NEVER BE
// DEALLOCATED! DON''T DO IT!
*c = 0;

On the other hand, you can point to other locations in the string by manipulating the pointer to the string:

// save the pointer, or better yet, copy it.
char *cpy = c;
// setup a counter
int i = 0;
// set the first n elements of the string (char array) to 0
while ( i++ < n ) cpy++ = 0;

Note that with the allocation done above, the final call of cpy++ = 0 is likely to overstep the bounds of the string.

You really need to read a good C reference on pointers and memory (I haven''t coded C in years; my post may be riddled with flaws). I use C++ and have switched to using the STL string class, std::string.

Share this post


Link to post
Share on other sites