Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass main's *argv[] to a function?

Tags:

I have a program that can accept command-line arguments and I want to access the arguments, entered by the user, from a function. How can I pass the *argv[], from int main( int argc, char *argv[]) to that function ? I'm kind of new to the concept of pointers and *argv[] looks a bit too complex for me to work this out on my own.

The idea is to leave my main as clean as possible by moving all the work, that I want to do with the arguments, to a library file. I already know what I have to do with those arguments when I manage to get hold of them outside the main. I just don't know how to get them there.

I am using GCC. Thanks in advance.

like image 259
Eternal_Light Avatar asked Oct 24 '11 22:10

Eternal_Light


People also ask

How do you pass argc and argv in C++?

To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. The value of argc should be non negative. argv(ARGument Vector) is array of character pointers listing all the arguments.

What does * argv [] mean?

argc stands for argument count and argv stands for argument values. These are variables passed to the main function when it starts executing. When we run a program we can give arguments to that program like − $ ./a.out hello.

What does char * argv [] mean in C?

The declaration char *argv[] is an array (of undetermined size) of pointers to char , in other words an array of strings. And all arrays decays to pointers, and so you can use an array as a pointer (just like you can use a pointer as an array).

What does int argc char * argv [] mean in C?

Command-line Arguments: main( int argc, char *argv[] ) Here argc means argument count and argument vector. The first argument is the number of parameters passed plus one to include the name of the program that was executed to get those process running.


2 Answers

Just write a function such as

void parse_cmdline(int argc, char *argv[])
{
    // whatever you want
}

and call that in main as parse_cmdline(argc, argv). No magic involved.

In fact, you don't really need to pass argc, since the final member of argv is guaranteed to be a null pointer. But since you have argc, you might as well pass it.

If the function need not know about the program name, you can also decide to call it as

parse_cmdline(argc - 1, argv + 1);
like image 80
Fred Foo Avatar answered Nov 01 '22 13:11

Fred Foo


Just pass argc and argv to your function.

like image 43
Basile Starynkevitch Avatar answered Nov 01 '22 15:11

Basile Starynkevitch