Command line arguments allow you to pass arguments or parameters to a program when it is run from the command line or terminal. In C, command line arguments can be accessed through the main
function. Here’s an example of how to use command line arguments in C:
#include <stdio.h> int main(int argc, char *argv[]) { // argc represents the number of command line arguments // argv is an array of strings containing the arguments printf("Number of arguments: %d\n", argc); // Loop through each argument and print its value for (int i = 0; i < argc; i++) { printf("Argument %d: %s\n", i, argv[i]); } return 0; }
In this example, argc
represents the number of command line arguments, including the program name itself. The argv
array is an array of strings (char*
) containing the actual arguments.
When you run the compiled program from the command line, you can provide arguments after the program name, separated by spaces. For example:
$ ./program arg1 arg2 arg3
In this case, argc
will be 4 (including the program name), and argv
will contain the following values:
argv[0]: "./program" argv[1]: "arg1" argv[2]: "arg2" argv[3]: "arg3"
You can access and process these arguments within your program as needed.