The Meaning Of argc And argv In main()
Updated:
TL;DR
When you want to pass arguments to the main function:
int argcis the argument count.char* argv[]is the argument vector, containing all the actual arguments as C strings.
The main() explained
The main function is a fundamental part of every C program. It’s mandatory to implement a definition (not just a declaration) of main, which serves as the entry point of your program.
The main function is called at program startup, after all objects with static storage duration are initialized. It is the designated entry point to a program that is executed in hosted environment (that is, with an operating system). The name and type of the entry point to any freestanding program (boot loaders, OS kernels, etc) are implementation-defined.
The proper definition of main()
There are two possible definitions that can be used. You can define main with no input parameter:
int main() {
/* main body... */
}
Or you can define main with two parameters, by convention named argc and argv:
int main(int argc, char* argv[]) {
/* main body... */
}
In another Dev Tip, we discuss the return type of main, a topic subject to a widespread programming mistake (spoiler: it must be int). Here we explain the role of argc and argv.
Sending arguments to a program
The input parameters argc and argv are used to send arguments to a program. The program receives arguments thanks to argv, which is a pointer to an array of C strings containig those arguments. Or to put it better, an array of pointers to C strings, each string containing an argument. The number of arguments, hence the number of elements of the argv array, is passed with argc.
Usually, argv[0] contains the program name, but this may not always be the case. Instead argv[argc] is always guaranteed to be a NULL pointer.
It is worth noting that argv can be written in two ways. This is just a matter of how to declare an array of pointers, which can be thought of as a pointer to pointers. Both versions mean exactly the same thing.
int main(int argc, char* argv[])
int main(int argc, char** argv)
Processing the arguments
In this simple program we print all the arguments that will be passed to it at the time of execution.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
for (int i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return EXIT_SUCCESS;
}
If we call this program argv_example and we run it with these arguments:
> path/argv_example this is a beautiful day
We will get this output:
Argument 0: path/argv_example
Argument 1: this
Argument 2: is
Argument 3: a
Argument 4: beautiful
Argument 5: day