Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a value to the array of command line arguments?

My application has entry point

int main(int argc, char *argv[])
{

}

I need to extend *argv array to n+1 and append a value. For example, I need to append "-app_ver".

I'm a newcomer in C++ (with Java background). I know that I can't change array size, so I need any solution (any approach copying array, etc.)

like image 399
Nodirbek Shamsiev Avatar asked Apr 12 '17 14:04

Nodirbek Shamsiev


2 Answers

To duplicate your argv, you can use a std::vector of pointers to char.

std::vector<const char*> new_argv(argv, argv + argc);

Then add the new element to it:

new_argv.push_back("-app_ver");
new_argv.push_back(nullptr); // or NULL if you are using an old compiler

Then replace argv with the new array:

argv = new_argv.data(); // or &new_argv[0] if you are using an old compiler
argc = argc + 1;

Note: at the end of normal arguments, there should be a null pointer. It's rarely used (though it's required by the Standard); if you are sure your further code doesn't use it, and you only want to add one element to your argv array, you can just overwrite the null pointer, and not use any replacement for argv. That is, disregard all the above code, and just do this:

argv[argc++] = "-app_ver";

However, this is dangerous - it will crash if you ever decide to add one more element, and it might crash if some code requires the presence of a null pointer after the last argument.

like image 53
anatolyg Avatar answered Oct 18 '22 17:10

anatolyg


Like cbuchart says, you have to create a new array or maybe a vector. Using vector and string object can be more simple than char* and array.

Exemple :

#include <vector>
#include <string>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    vector<string> list;
    for ( int i = 1 ; i < argc ; i++){
        string tmp (argv[i]);
        list.push_back(tmp); // add all arguments to the vector
    }

    cout << "number of given arguments : " << list.size() << endl;

    list.push_back("-app_ver"); // add one string to the vector

    for ( int i = 0 ; i < list.size() ; i++){
        cout << list[i] << endl; // acces data of the vector
    }

}
like image 36
baddger964 Avatar answered Oct 18 '22 15:10

baddger964