c++ - How do I return a char array from a function?

ID : 131366

viewed : 8

Tags : c++arraysfunctionreturnc++

Top 5 Answer for c++ - How do I return a char array from a function?

vote vote


Best as an out parameter:

void testfunc(char* outStr){   char str[10];   for(int i=0; i < 10; ++i){     outStr[i] = str[i];   } } 

Called with

int main(){   char myStr[10];   testfunc(myStr);   // myStr is now filled } 
vote vote


You have to realize that char[10] is similar to a char* (see comment by @DarkDust). You are in fact returning a pointer. Now the pointer points to a variable (str) which is destroyed as soon as you exit the function, so the pointer points to... nothing!

Usually in C, you explicitly allocate memory in this case, which won't be destroyed when the function ends:

char* testfunc() {     char* str = malloc(10 * sizeof(char));     return str; } 

Be aware though! The memory pointed at by str is now never destroyed. If you don't take care of this, you get something that is known as a 'memory leak'. Be sure to free() the memory after you are done with it:

foo = testfunc(); // Do something with your foo free(foo);  
vote vote


A char array is returned by char*, but the function you wrote does not work because you are returning an automatic variable that disappears when the function exits.

Use something like this:

char *testfunc() {     char* arr = malloc(100);     strcpy(arr,"xxxx");     return arr; } 

This is of course if you are returning an array in the C sense, not an std:: or boost:: or something else.

As noted in the comment section: remember to free the memory from the caller.

vote vote


As you're using C++ you could use std::string.

vote vote


With Boost:

boost::array<char, 10> testfunc() {     boost::array<char, 10> str;      return str; } 

A normal char[10] (or any other array) can't be returned from a function.

Top 3 video Explaining c++ - How do I return a char array from a function?