Reputation: 593
In c++ I've got a main function with
int argc, char * argv[]
I need to access the data in argv[]
(i.e the arguments) in another function.
I am going to declare a global variable, a pointer to the char **argv
.
How do I do this?
Upvotes: 3
Views: 1497
Reputation: 171117
In C++, usually* the best way to handle argv
is this:
int main(int argc, char **argv)
{
std::vector<std::string> args(argv, argv + argc);
}
Now you have args
, a correctly constructed std::vector
holding each element of argv
as a std::string
. No ugly C-style const char*
in sight.
Then you can just pass this vector or some of its elements as you need.
* It carries the memory & time overhead of dynamically allocating one copy of each argv
string. But for the vast majority of programs, command-line handling is not performance-critical and the increased maintainability and robustness is well worth it.
Upvotes: 12
Reputation: 3098
Global variables should be avoided and you should prefer passing arguments. Anyway, you can just use:
char **global_argv = NULL;
int main(int argc, char * argv[]){
...
global_argv = argv;
...
}
A better way would be:
void my_fun1(int argc, char **argv); // Passing all the program arguments
void my_fun2(char *arg); // Passing just the one you need
int main(int argc, char * argv[]){
...
my_fun1(argc, argv);
my_fun2(argv[3]); // Supposing you need the 3rd parameter (fourth on argv)
...
}
Upvotes: 6