Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return a char array from a function?

I've tried the following:

char[10] testfunc()
{
    char[10] str;

    return str;
}
like image 555
Datoxalas Avatar asked Apr 14 '11 08:04

Datoxalas


People also ask

Can you return char [] in C?

Strings in C are arrays of char elements, so we can't really return a string - we must return a pointer to the first element of the string.

Which function is used to return a character?

Explanation: The strchr() function is used to return a pointer to the located character if character does not occur then a null pointer is returned.


3 Answers

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
}
like image 96
Xeo Avatar answered Oct 09 '22 16:10

Xeo


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); 
like image 27
Marijn van Vliet Avatar answered Oct 09 '22 15:10

Marijn van Vliet


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.

like image 13
Felice Pollano Avatar answered Oct 09 '22 16:10

Felice Pollano