Reputation: 27210
we declare main() as
int main(int argc, char *argv[])
and pass some argument by command line and use it
as argv[1]
, argv[2]
in main() function definition but what if i want to use that in some other function's definition ?
one things i can do it always pass that pointer char** argv
from main() to that function by argument. But is there any other way to do so?
Upvotes: 0
Views: 197
Reputation: 726539
In order to make data available to other functions, you need to pass it as a parameter, or make it available through a global (not recommended) or a static variable.
static char** args cmd_args;
static int cmd_arg_count;
int main(int argc, char** argv) {
cmd_arg_count = argc;
cmd_args = argv;
do_work();
return 0;
}
void do_work() {
if (cmd_args > 1) {
printf("'%s'\n", cmd_args[1]);
}
}
The best approach is to make a function that parses command line parameters, and stores the results in a struct
that you define specifically for the purpose of representing command line arguments. You could then pass that structure around, or make it available statically or globally (again, using globals is almost universally a bad idea).
Upvotes: 1
Reputation: 16597
one things i can do it always pass this value from main() to that function by argument. But is there any other way to do so?
No. Passing the argc
and argv
to other functions is perfectly valid.
int main(int argc, char *argv[])
{
typedef struct _cmdline_arg_struct {
// all your command line arguments go here
}cmdline_arg_struct;
/* command line arguments - parsed */
cmdline_arg_struct *pc = (cmdline_arg_struct *) malloc(sizeof(cmdline_arg_struct));
if (parse_cmdline_args(&pc, argc, argv) == PARSE_FAILURE) {
usage();
return 0;
}
/* Now go through the structure and do what ever you wanted to do.. *?
}
Upvotes: 1
Reputation: 162164
but what if i want to use that in some other function's definition?
You mean have another set of parameters for main? That's not possible, because main is defined in the C standard as either
int main();
or
int main(int, char*[]);
And it makes sense: The first parameter tells you the number of parameters given on the command line, the second contains the array of pointers to those parameters.
It's your responsibility to make sense of those parameters and pass them to other functions. Use string conversion functions if you need to make them numbers.
Upvotes: 0
Reputation: 596
You could have code in main() to store the values in non-local variables, and then refer to those variables from other functions.
Upvotes: 0
Reputation: 3922
Just pass the pointer?
int main(int argc, char** argv) {
do_something_with_params(argv);
}
void do_something_with_params(char** argv) {
// do something
}
Or if you mean passing single arguments:
int main(int argc, char** argv) {
do_something_with_argv1(argv[1]);
do_something_with_argv2(argv[2]);
}
void do_something_with_argv1(char* arg) {
// do something
}
void do_something_with_argv2(char* arg) {
// do something
}
Upvotes: 2