I want to initialize/set char *argv[]
inside the main()
so that I can use argv[1], argv[2]...
later in my program.
Up to now, I know how to do this in two ways:
For
int main()
, use one line as:int main() { char *argv[] = {"programName", "para1", "para2", "para3", NULL}; }
Note that, using
NULL
in the end is because the pointers in theargv
array point to C strings, which are by definitionNULL
terminated.For
int main(int argc, char* argv[])
, I have to use multiple lines as:int main(int argc,char* argv[]) { argv[0] = "programName"; argv[1] = "para1"; argv[2] = "para2"; argv[3] = "para3"; }
My question is that how can I combine these two methods together, i.e. use only one line to initialize it for int main(int argc, char* argv[])
? Particularly, I want to be able to do like this (this will be wrong currently):
int main(int argc, char* argv[])
{
argv = {"programName", "para1", "para2", "para3", NULL};
}
How can I be able to do this?
Edit: I know argv[]
can be set in Debugging Command Arguments
. The reason that I want to edit them in main()
is that I don't want to bother to use Debugging Command Arguments
every time for a new test case (different argv[]
setting).
mani()
scope. – Absoluteargc
is read-only. Actually, I need to setargc
as well. Deleted already as not relevant to this question. – Absoluteargc
andargv
(or whatever you name them) are local tomain()
and you can do anything you want with them. The actual command-line parameters are read-only in standard C++, and if they can be accessed in a different way, it's through the OS API. What is it you're trying to solve by modifying the arguments? – Placativestd::vector<std::string>
. You can easily initialize such a vector from argc and argv (viastd::vector<std::string> const args(argv, argv + argc);
) or you can initialize it yourself with whatever strings you choose if you want to use a set of known strings at runtime. If you're learning C++, I'd recommend this approach. It's much safer, harder to screw up, and requires fewer asterisks. – Beenargv
in main, it'll be only at compile-time, your hands are tied at debug time even then. – Ilsonly at compile-time
? – Absoluteargv
say like Emilio's solution, wouldn't you have to recompile it every time you changen_argv
? If yes, then how does it help you debug, since every time you need a different string, you'll've to modifyn_argv
, compile and run the program. Correct? – Ilsbreakpoints
for different test cases? – Absolute