views:

233

answers:

4

How do I assign a sequence of character strings to a char ** argv variable in a program? Its a command line argument. I'm currently trying to convert an .exe app to a dll.

For example:

{ "string1", "string2", "string3" } --- > char ** argv variable

My problem is somehow realted to this: http://stackoverflow.com/questions/1015944/how-does-an-array-of-pointers-to-pointers-work/1015970#1015970 but I can't get it to work using the snippet shown there. Help!

+8  A: 

const char* argv[] = {"string1", "string2", "string3", 0};

If the arguments aren't compile time constants I would do something like:

std::vector<const char*> arguments;
arguments.push_back(somePointer);
arguments.push_back(someOtherPointer);
arguments.push_back(0);
const char** argv = &arguments[0];

EDIT: Using PaxDiablos information that an argv-array should be null terminated.

Andreas Brinck
@Andreas, if it's a true argv (as in what main expects), it should have a fourth pointer set to NULL. That may not, however, be part of the requirements for this situation.
paxdiablo
That's better, deleting mine since it adds nothing new now (and because it uses malloc - ugh!).
paxdiablo
I can't remember how they're stored internally, but in this example would std::vector<std::string> be usable?
John
@John No, there's no way to directly pass a `std::vector<std::string>` to a function expecting a `char**`.
Andreas Brinck
A: 

I can't use vectors. Any other answers?

Rock
what exactly is your problem? The answer to your question is already given above
chrmue
can you explain why you can't use vectors? It seems this must be a Windows app (since you mention DLLs) meaning STL support should be good.
John
A: 

what about getopt?

teZeriusz
A: 

Note that Andreas Brincks answer is really what you want to do, where vector does all the heavy lifting of allocation and provides exception safety. I strongly suggest that you look into changing whatever reason there is for not being able to use vector. But if you really really cannot do so, I guess you could do something along the lines of the below code:

int numArgs = YOUR_NUMBER_HERE;

char **myArgv = new char*[numArgs+1];

for (int i=0; i<numArgs; ++i) {
    myArgv[i] = new char[at least size of your argument + 1];
    strncpy(myArgv[i], whereever your string is, buffer size);
    myArgv[buffer size] = '\0';
}
myArgv[numArgs] = NULL;


// use myArgv here


// now you need to manually free the allocated memory
for (int i=0; i<numArgs; ++i) {
    delete [] myArgv[i];
}
delete [] myArgv;
villintehaspam