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

I've tried the following:

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

    return str;
}

This question is related to c++ arrays function return

The answer is


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.


When you create local variables inside a function that are created on the stack, they most likely get overwritten in memory when exiting the function.

So code like this in most C++ implementations will not work:

char[] populateChar()
{
    char* ch = "wonet return me";
    return ch;
}

A fix is to create the variable that want to be populated outside the function or where you want to use it, and then pass it as a parameter and manipulate the function, example:

void populateChar(char* ch){
    strcpy(ch, "fill me, Will. This will stay", size); // This will work as long as it won't overflow it.
}

int main(){
    char ch[100]; // Reserve memory on the stack outside the function
    populateChar(ch); // Populate the array
}

A C++11 solution using std::move(ch) to cast lvalues to rvalues:

void populateChar(char* && fillme){
    fillme = new char[20];
    strcpy(fillme, "this worked for me");
}

int main(){
    char* ch;
    populateChar(std::move(ch));
    return 0;
}

Or this option in C++11:

char* populateChar(){
    char* ch = "test char";
    // Will change from lvalue to r value
    return std::move(ch);
}

int main(){
    char* ch = populateChar();
    return 0;
}

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


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

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.


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to return

Method Call Chaining; returning a pointer vs a reference? How does Python return multiple values from a function? Return multiple values from a function in swift Python Function to test ping Returning string from C function "Missing return statement" within if / for / while Difference between return 1, return 0, return -1 and exit? C# compiler error: "not all code paths return a value" How to return a struct from a function in C++? Print raw string from variable? (not getting the answers)