We can also pass arguments to the main function and the main function can accept two arguments. One of these arguments is an integer and the second is an array of strings.
The declaration of the main looks like this:
int main(int argc, char *argv[])
Here, argc
(argument count) stores the number of the arguments passed to the main function and argv
(argument vector) stores the array of the one-dimensional array of strings. So, the passed arguments will get stored in the array argv
and the number of arguments will get stored in the argc
.
We can pass these arguments through the command line (while executing the file). For example, we can pass arguments to the main function while executing a file (with name filename) as - ./filename
abc
def
. Here, we have passed three arguments to the main function. The first is the name of the program itself i.e., "./filename", second is the string "abc" and the third is "def". We can easily verify this using the code given below.
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("%d\n",argc);
printf("%s\n",argv[0]);
printf("%s\n",argv[1]);
printf("%s\n",argv[2]);
return 0;
}
Command given to run the file:
./filename abc def
Output
3
./filename
abc
def