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

Introduction

When programming in C/C++, it is sometimes necessary to return a char* array from a function. This can be done in a few different ways, depending on the specific needs of the program. In this article, we will discuss the various methods of returning a char* array from a C/C++ function, as well as the advantages and disadvantages of each approach. We will also provide some examples of code to help illustrate the concepts discussed.

Solution

The following code snippet shows how to return a char* array from a C/C++ function:

// Function to return a char* array
char* getCharArray()
{
// Create a char array
char arr[10] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’};

// Return the char array
return arr;
}

// Main function
int main()
{
// Call the function
char* arr = getCharArray();

// Print the array
for (int i = 0; i < 10; i++) printf("%c ", arr[i]); return 0; }

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.