Why does C provide both argc and argv for command-line arguments?
Asked by
MellowCedar42
I'm learning how command-line arguments work in C. My program is:
#include
int main(int argc, char *argv[]) {
printf("argc: %dn", argc);
}
After compiling it with `gcc main.c -o passwd`, I get different results depending on how I run it:
`./passwd` prints `argc: 1`
`./passwd 1 4 8 4 5` prints `argc: 6`
I understand that the program name is counted as the first argument, but I'm wondering why a program would need to count the arguments instead of simply printing the count. What is the practical purpose of `argc` and `argv`, and what kinds of programs use them?
Answers
Command-line tools use this constantly. For example, when you run `gcc main.c -o passwd`, the compiler receives strings representing the command name and each argument, then uses them to decide which source files and options to process. Other programs use the same mechanism for filenames, flags, input values, and configuration choices.
Reply to this answer
There is a small technical nuance: command-line argument lists are conventionally terminated by a null pointer after the last argument, but `argc` is still the standard, explicit count used by `main` and makes the intended number of entries immediately available. In normal code, use `argc` to control indexing and remember that the user-provided arguments begin at `argv[1]`, not `argv[0]`.
Reply to this answer
`argv` contains the command-line arguments as strings, while `argc` tells you how many there are. C arrays do not carry their length with them, so a function receiving an array usually needs a separate count. A typical loop looks like this:
for (int i = 0; i < argc; i++) {
printf("argv[%d] = %sn", i, argv[i]);
}
The first entry, `argv[0]`, is normally the program name or its path. In your second example, the six entries are the program name plus the five values you typed.
Reply to this answer
The program you wrote is just a demonstration, so there is no practical need to print the count by itself. A more realistic use would be validating input:
if (argc < 3) {
fprintf(stderr, "Usage: %s input outputn", argv[0]);
return 1;
}
That prevents the program from assuming arguments exist when the user did not provide them. The argument count is also useful for looping over every supplied argument.
Reply to this answer
Printing `argc` is mostly useful for learning or debugging. In a real program, its important job is to tell you how many entries are available in `argv`, so you can process them safely without reading beyond the array. For example, a program can check that the user supplied the required number of options before accessing `argv[1]`, `argv[2]`, and so on.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions