command line arguments c
To pass command line arguments in C, you can make use of the argc
and argv
parameters in the main
function.
Here's an example:
#include <stdio.h>
int main(int argc, char *argv[]) {
// argc stores the number of command line arguments
// argv is an array of strings that holds the arguments
// Print the number of arguments
printf("Number of arguments: %d\n", argc);
// Print each argument
for (int i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}
In this example, argc
stores the number of command line arguments passed to the program. argv
is an array of strings, where each element represents an argument. The first argument (argv[0]
) is the name of the program itself.
You can compile and run this program with command line arguments. For example, if you compile the program and run it with ./program arg1 arg2 arg3
, it will output:
Number of arguments: 4
Argument 0: ./program
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3
Note that the number of arguments includes the program name itself.