[Solved] How to return char* array in c/c++ function? [closed]


Unless you have a global char*[] you want to return from this function, yes, you need dynamic allocation, it is the only way you can safely return a variable created inside the function, for all variables stored in the stack will be destroyed as soon as the function finishes.

char** myfun()
{
     char **p = new char*[10];
     return p;
     //or return new char*[10];
}

int main() {

    char **pp = test();

    char *p = "aaa";

    pp[0] = p;

    delete[] pp; //if you allocate memory inside the array, you will have to explicitly free it:
                 //Example: pp[1] = new char("aaa"); would require delete p[1]; 

}

–Edit

You don’t HAVE TO use dynamic allocation, you could return a local static variable. Keep in mind that this is not a good approach though: the function would not be thread safe or reentrant.

2

solved How to return char* array in c/c++ function? [closed]