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 call genArgs, you know how many arguments you want to pass. Is this correct? If so (and if you are using C++11) then you can use std::array in the calling function. So instead of this:
char** arglist = genArgs (4, "MyArg1", mYaRG2", "LastArg", 0) ;
somefunc (arglist) ;
delete[] arglist ;
you can do it this way:
#include <array>
std::array<char*, 4> arglist { "MyArg1", mYaRG2", "LastArg", 0 } ;
somefunc (&arglist[0]) ;
But there is really nothing wrong with the first solution, unless you are a C++ ascetic. (However, you do need a return toRet ; statement in genArgs!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With