You must construct a new array. Here an example:
int new_argc = argc + 2;
char** new_argv = new char*[new_argc];
new_argv[argc + 1] = nullptr;
for (int ii = 0; ii < argc; ++ii) {
new_argv[ii] = argv[ii];
}
new_argv[argc] = new char[strlen("-app_ver") + 1]; // extra char for null-terminated string
strcpy(new_argv[argc], "-app_ver");
// use new_argc and new_argv
delete[] new_argv[argc];
delete[] new_argv;
See that I've allocated only the new parameters for the sake of optimization. To create a full copy you'll have to allocate the memory for the previously existing parameters.
Just be careful with those manual memory allocations: delete them when finishing. You only have to delete the ones you've created.
On the other hand, as argv
and argc
are usually used in the main
function it is not a big deal (the memory-leak).
Remarks
As I don't know the future use of these new command line arguments, this solution tries to keep with the original data types of the main
function. If it is passed to Boost or Qt, then the char**
cannot be obtained from more direct options such as when using std::vector<std::string>
. To start with, std::string::c_str()
returns a const char*
, and those pointers are not consecutive in memory.
A safer option (no manual deletes) can be:
int new_argc = argc + 1;
std::vector<std::unique_ptr<char>> new_argv_aux(new_argc); // automatically destroyed
for (int ii = 0; ii < argc; ++ii) {
new_argv_aux[ii].reset(new char[strlen(argv[ii]) + 1]);
strcpy(new_argv_aux[ii].get(), argv[ii]);
}
new_argv_aux[argc].reset(new char[strlen("-app_ver") + 1]);
strcpy(new_argv_aux[argc].get(), "-app_ver");
// Now the actual double pointer is extracted from here
std::vector<char*> new_argv(new_argv_aux.size());
for (size_t ii = 0; ii < new_argv_aux.size(); ++ii) {
new_argv[ii] = new_argv_aux[ii].get(); // soft-reference
} // last element is null from std::unique_ptr constructor
use_here(new_argc, new_argv.data());
std::vector<std::string>
orstd::vector<std::string_view>
and then appending your new value where you want? – Sympathinchar *
of sizeargc + 2
, copy the originalargc
strings over fromargv[]
, then add your extra value and a finalNULL
in the last two elements. – Foundation