C Programming: Exploring Command-Line Arguments in main()
Understanding Command-Line Arguments in C: main() Function
In C programming, the main function can accept command line arguments that are provided when you run the program from the command line. The main function signature can be one of the following:
Standard main function signature:
C Programming
int main(int argc, char *argv[])
Alternative signature with explicit data types:
c Programming
int main(int argc, char **argv)
Here's a breakdown of the components:- int argc: Stands for "argument count" and represents the number of command line arguments passed to the program.
- char *argv[] or char **argv: Stands for "argument vector" and represents an array of strings that holds the command line arguments. Each element of the array (argv[0], argv[1], argv[2], and so on) is a string representing a command line argument.
Here's a simple example of how you can use command line arguments in a C program:
C Programming
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Number of arguments: %d\n", argc);
for (int i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}
If you compile this program and run it from the command line like this:
bash
./program arg1 arg2 arg3
You will get output similar to:yaml
Number of arguments: 4
Argument 0: ./program
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3
Keep in mind that the first argument (argv[0]) is typically the name of the program itself. The actual arguments start from argv[1]. The total number of arguments, including the program name, is stored in argc.