3

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: How does an array of pointers to pointers work? but I can't get it to work using the snippet shown there. Help!

Community
  • 1
  • 1
Rock
  • 31
  • 2
  • Are you trying to assign the three command-line arguments to three separate char* variables in your program, or are you trying to assign three variables into a char** you have declared yourself? – Paul Stephenson Jan 12 '10 at 08:42
  • 1
    I'm trying to assign 3 strings to the char** I have declared. I might also reassigned a different sequence of strings on the later part of the program. What is the correct way to do this? – Rock Jan 12 '10 at 08:51
  • Why on Earth would you want to modify the passed-in parameters? – John Dibling Jan 12 '10 at 15:37

3 Answers3

8

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
  • 51,293
  • 14
  • 84
  • 114
  • 1
    @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 Jan 12 '10 at 08:54
  • That's better, deleting mine since it adds nothing new now (and because it uses malloc - ugh!). – paxdiablo Jan 12 '10 at 09:00
  • I can't remember how they're stored internally, but in this example would std::vector be usable? – Mr. Boy Jan 12 '10 at 11:44
  • @John No, there's no way to directly pass a `std::vector` to a function expecting a `char**`. – Andreas Brinck Jan 12 '10 at 13:20
0

what about getopt?

teZeriusz
  • 81
  • 2
  • 8
0

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
  • 8,540
  • 6
  • 45
  • 76