Create an array of char * pointers from a function

I have a C ++ function that I have to go to char* arguments[]. The prototype of this function is as follows: void somefunc(char* arguments[])

To pass the above array to this function, I generate this array from another function that can return this output to me char* array, and it looks something like this.

char** genArgs(int numOfArgs,...)
{
    va_list argList;    
    char** toRet = new char*[numOfArgs];
    va_start (arguments, numOfArgs);
    for(int cnt = 0; cnt < numOfArgs ; ++cnt)
        toRet[cnt] = va_arg(argList, char*);

    va_end(arguments);
}

I am confused how to correctly write the above function correctly, given that I will pass the input to something like: genArgs(3, a.c_str(), b.c_str(), c.c_str())or genArgs(2, a.c_str(), b.c_str())
How can I generate the above char * array without using char ** (since it would have to be deleted before returning from function to avoid memory leak).

+3
source share
3 answers

genArgs, , , genArgs, , . ? ( C++11), std::array . :

char** arglist = genArgs (4, "MyArg1", mYaRG2", "LastArg", 0) ;
somefunc (arglist) ;
delete[] arglist ;

:

#include <array>
std::array<char*, 4> arglist { "MyArg1", mYaRG2", "LastArg", 0 } ;
somefunc (&arglist[0]) ;

, ++. ( , return toRet ; genArgs!)

+3

,

: , delete[] , new[], , .

:

// This allocates args; we now own the pointer
char **argsToPass = genArgs(2, a.c_str(), b.c_str());
// Make the call as usual
somefunc(argsToPass);
// Now that args are no longer needed, we delete them:
delete [] argsToPass;
+2

The usual way would be to use an object that controls the lifetime of the array (for example, std::vector<char*>or std::unique_ptr<char*[]>), and then return it (to guarantee a possible freeing of memory by system type):

std::vector<char*> genArgs(int numOfArgs,...)
{
    std::vector<char*> toRet;
    toRet.reserve(numOfArgs);
    va_list argList;
    va_start(argList, numOfArgs);
    for(int cnt = 0; cnt < numOfArgs ; ++cnt) {
        toRet.push_back(va_arg(argList, char*));
    }
    va_end(arguments);
    return toRet;
}

To use this, follow these steps:

somefunc(&genArgs(3, a.c_str(), b.c_str(), c.c_str()).front());
0
source

All Articles