Return char-array

Started by
4 comments, last by peter86 21 years, 6 months ago
How should I return a char-array and how should I declare the function?
Advertisement
if you actually DO want to return a char array it would be:
char* daFunctionName(void) 

but then you must dynamically allocate the char array in your function, and make sure that it is delete[] d from wherever the function was called (or you will get memory leaks).

i prefer to pass the char array into the function as a parameter, mess with it in there, and return true if it is successful. that way the array is allocated BEFORE the function is called, and this makes it more obvious (and trherefore easier to remember) to delete[] the array afterwards.
--- krez ([email="krez_AT_optonline_DOT_net"]krez_AT_optonline_DOT_net[/email])
probably the safest and most common way would be to make it an output parameter.
assuming c/c++:

void
test_func()
{
char fill_me_in[128];
func(fill_me_in);
}

char *
func(char *fill_me_in)
{
memset(fill_me_in, 0, 128);
}

alternatively, you can allocate memory inside the function, but the responsibility to free it falls on the caller:

void
test_func()
{
char *ret_val = func();
}

char *
func()
{
char *stuff = malloc(128);
memset(stuff, 0, 128);
return stuff;
}





[edited by - dedrick on October 18, 2002 4:45:07 PM]

[edited by - dedrick on October 18, 2002 4:45:29 PM]
dedrickwww.whiteknucklegames.com
quote:Original post by krez
i prefer to pass the char array into the function as a parameter, mess with it in there, and return true if it is successful. that way the array is allocated BEFORE the function is called, and this makes it more obvious (and trherefore easier to remember) to delete[] the array afterwards.


I''m glad I''m not the only one to do it that way. I was afraid I was doing it that way for no good reason.
Aaargh! Everyone save your workspaces before your program locks up your computer!
Can´t I return it in a this pointer?
If yes, then could anyone give an example?
this is a pointer to the object that a member function was called from. this has no meaning outside of that context.
--- krez ([email="krez_AT_optonline_DOT_net"]krez_AT_optonline_DOT_net[/email])

This topic is closed to new replies.

Advertisement