How do I return a char array from a function?

171,686

Solution 1

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
}

Solution 2

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); 

Solution 3

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.

Solution 4

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

Solution 5

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.

Share:
171,686
Datoxalas
Author by

Datoxalas

I am a happy programmer!

Updated on July 09, 2022

Comments

  • Datoxalas
    Datoxalas almost 2 years

    I've tried the following:

    char[10] testfunc()
    {
        char[10] str;
    
        return str;
    }
    
  • DarkDust
    DarkDust about 13 years
    Please also pass the capacity as argument, it's too fragile this way.
  • DarkDust
    DarkDust about 13 years
    Also, a strncpy or memcpy would be more efficient when copying out the result.
  • tenpn
    tenpn about 13 years
    This does a copy on exit, rather than pass a reference. May not be a problem but for large arrays this could be a substantial cost. However with use of the return value optimisation (en.wikipedia.org/wiki/Return_value_optimization) you could completely elide the copy.
  • DarkDust
    DarkDust about 13 years
    A char array is not the same as a char pointer. See the C FAQ question 6.2.
  • Alberto
    Alberto over 6 years
    Sorry Felice, but you haven't understood my point; the memory leak is not in the assignment (and strcpy does not help at all, either). It's that you are reserving memory via malloc, but no one is deallocating that memory (calling free() in this case). You should note that, in this case, the caller function should check if the poiner is not null, and then free() it after it's used. Otherwise, you are introducing a memory leak. Anyway, it's a bad practice and should be avoided like hell.
  • Felice Pollano
    Felice Pollano over 6 years
    @mydaemon well I can't write all the code of the entire program, it is clear that the OP has to free the memory after its usage. As you pointed off, the code before the edit was wrong, because it will cause the loss of the allocated pointer.
  • Alberto
    Alberto over 6 years
    I do agree with the change, but as an advice, never assume the op will know the same things than you. It takes literally 30 seconds to add a note: you should be calling free from the caller function".
  • mostlyWright
    mostlyWright over 3 years
    to be fair Marjin said 'similar'. From the linked FAQ "Arrays are not pointers, though they are closely related (see question 6.3) and can be used similarly." which is basically what Marjin said.
  • Danilo
    Danilo about 3 years
    As you are answering the question, you could stay on topic. User asked how does one return an char array from a function, not what should s/he use. The reasoning why exactly char array is unknown. It could be a practice, it could be a homework, it could be looking under the hood... best not to assume.
  • Kai Petzke
    Kai Petzke about 3 years
    Instead of boost::array, one can also use std::array and avoid the dependency on boost.
  • SteeveDroz
    SteeveDroz over 2 years
    As stated here, you need to cast the return of malloc().