Work with char ** argv

How to assign character string sequence to char ** argv variable in program? Its a command line argument. I am currently trying to convert a .exe application to dll.

For instance:

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

My problem somehow comprehended this:   How does an array of pointers to pointers work? but I can't get it to work using the snippet shown there. Help!

+3
source share
3 answers

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

If the arguments are not 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];

: PaxDiablos , argv -array .

+8
0

Note that Andreas Brincks answers what you want to do, where the vector does all the heavy deselection and ensures exception safety. I highly recommend that you study any reason why you cannot use the vector. But if you really can't do this, I think you could do something according to the code below:

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;
0
source

Source: https://habr.com/ru/post/1728152/


All Articles