I have a C++ function to which I have to pass char* arguments[]. The prototype of this function is as follows:
void somefunc(char* arguments[])
To pass the above array to this function, I am generating this array from another function which can return me this char* array output, and this looks somehwhat 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 actually write the above function correctly, given that I will be passing the inputs to function 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 this would have to be deleted before returning from the function to avoid memory leak).
From your declaration of
genArgs, it seems that whenever you callgenArgs, you know how many arguments you want to pass. Is this correct? If so (and if you are usingC++11) then you can usestd::arrayin the calling function. So instead of this:you can do it this way:
But there is really nothing wrong with the first solution, unless you are a C++ ascetic. (However, you do need a
return toRet ;statement ingenArgs!)