Advertisement

function returning a string

Started by September 30, 2001 05:26 PM
2 comments, last by glGreenhorn 23 years, 4 months ago
Okay, I''ve been messing around with this for four hours now and now I''m gonna post it: how do I make a function return a string? I suppose it''s something like this: const char* Function(const int value); //prototype //**// char buf[40]; //inside some other routine strcpy(buf, Function(12)); MessageBox(buf); //displays what Function returned //**// const char* Function(const int value) //the actual function { if(value == 12) return "peekaboo"; // } Thankszzz!
Remember that a string is an array. You pass the address around, not the whole thing. The problem with this is, any memory that is auto allocated in a function is cleaned up afterwards, so you have to dynamically allocate memory and hope that the function you return it to frees it. This is how that''s done:
  char *GetStr(void) {  char *Str = (char *) malloc(sizeof(char) * 10);  strcpy(Str,"ABCDEFGHI");  return Str;}int main(void) {  char *MyStr = GetStr();  /* Use MyStr */  free(MyStr);  return 0;}  

There''s a better method though, and this is how it is often done:
  void GetStr(char *Str, unsigned int Len) {  if(Len < 10) *Str = NULL;  else strcpy(Str,"ABCDEFGHI");}int main(void) {  char MyStr[10];  GetStr(MyStr,10);  /* Use MyStr */  return 0;}  

See why that''s better? No memory leakage .

[Resist Windows XP''s Invasive Production Activation Technology!]
Advertisement
you need to know the string functions by heart.

consult the msdn and commit them to memory. these examples are fine, but messing up with strings is a major source of memory leaks so don''t cut and paste this without really understanding what is going on and why it works the way it does.

Thanks N&V. I wasn''t planning on copypasting

This topic is closed to new replies.

Advertisement