What does main get?
In C, the main
function typically takes two parameters: argc
(argument count) and argv
(argument vector). These parameters allow you to pass command-line arguments to your program.
Here's a simple example to illustrate how to use these parameters:
#include <stdio.h>
int main(int argc, char *argv[]) {
// Check if there are command-line arguments
if (argc > 1) {
// Print the program name
printf("Program name: %s\n", argv[0]);
// Print the command-line arguments
printf("Arguments passed:\n");
for (int i = 1; i < argc; i++) {
printf("%d: %s\n", i, argv[i]);
}
} else {
printf("No command-line arguments passed.\n");
}
return 0;
}
In this example, argc
represents the number of command-line arguments, and argv
is an array of strings containing those arguments. argv[0]
is the program name, and the subsequent elements (argv[1]
, argv[2]
, etc.) are the actual command-line arguments.
Compile and run the program with command-line arguments to see how it works. For example:
./program_name arg1 arg2 arg3
In this case, argc
would be 4, and argv
would be an array containing the program name and the three arguments.
Keep in mind that the main
function's signature must be one of the following:
int main(void)
or
int main(int argc, char *argv[])
The return type can be void
or int
, and argv
is an array of strings (char*
).