How do I return a char array from a function? How do I return a char array from a function? arrays arrays

How do I return a char array from a function?


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}


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 foofree(foo); 


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.