• Announcements

Archived

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

Return char-array

Recommended Posts

How should I return a char-array and how should I declare the function?

Share on other sites
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.

Share on other sites
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]

Share on other sites
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.

Share on other sites
Can´t I return it in a this pointer?
If yes, then could anyone give an example?

Share on other sites
this is a pointer to the object that a member function was called from. this has no meaning outside of that context.

• Partner Spotlight

• Forum Statistics

• Total Topics
627689
• Total Posts
2978648

• 13
• 14
• 12
• 10
• 12