⚙️ C programming basics · Class 10 · Lesson 12 of 18 · Free
Command-Line Arguments in C – argc and argv Explained
⏱ About 30 minutes · ▶ run real C here — nothing to install · no sign-in
In this lesson you will
- Read command-line arguments with argc and argv
- Convert argument text to numbers safely with atoi and strtol
- Use arguments as file names and commands, and print a usage message when they are wrong
Your marks-average program asks "Enter marks:" every single time. Real tools work differently: you type `average 78 91 66` and get the answer at once. Those extra words after the program name are command-line arguments, and C hands them to main.
What are argc and argv in C?
So far main had no parameters: `int main(void)`. It can also take two: `int main(int argc, char *argv[])`.
argc (argument count) is how many words were typed, including the program name. argv (argument vector) is an array of strings (Lesson 3) holding those words. argv[0] is the program's name, argv[1] the first real argument, and so on.
On a computer you would compile and run it like `gcc args.c -o args` and then `./args Riya 10 B`. On this page, the arguments box does the typing for you. Try it: add your own name as another argument and run again.
argc = 4 argv[0] = "program" argv[1] = "Riya" argv[2] = "10" argv[3] = "B"
💡 argv[0] can look different on different computers, e.g. ./args or C:\code\args.exe.
How do you convert command-line arguments to numbers in C?
Every argument is text, even "78". You cannot add two strings. You must turn them into numbers first.
`atoi` (ASCII to int, from <stdlib.h>) does that. Here the program adds all the marks it was given, then prints the average.
Notice the loop starts at 1, to skip the program name. Try it: add another mark like 85 to the arguments.
Subjects: 3 Total: 235 Average: 78.3
💡 A usage message tells the user how to run the program when the arguments are missing.
Why is strtol safer than atoi in C?
atoi has a weakness. For "abc" it returns 0, and for "9x" it returns 9. It never tells you the text was wrong.
`strtol` (string to long) also gives you a pointer to the first character it could NOT read. If that character is not the end of the string ('\0'), the text was not a clean number.
This program checks each argument and skips bad ones. Try it: change "9x" to "95" and run again.
Skipping "9x": not a whole number Skipping "abc": not a whole number Added 2 numbers, total = 200
💡 `end == argv[i]` means not even one digit was read.
How do you pass a file name as a command-line argument in C?
Many real tools take a file name as an argument. That way the same program works on any file, with no change to the code.
Here argv[1] is a file of attendance records, read with fscanf like in Lesson 5. The program counts how many days each student was present.
Always check that fopen did not return NULL: the user may type a file name that does not exist. Try it: change the argument to "june.txt" and see the error message.
Aman 20 22 Diya 22 22 Kabir 17 22
Attendance from may.txt Aman 20 / 22 days Diya 22 / 22 days Kabir 17 / 22 days
How do you make a command-line tool with commands in C?
Tools like git use the first argument as a command: `git add`, `git commit`. You can do the same with strcmp (Lesson 3).
Remember: compare strings with strcmp, never with ==. strcmp returns 0 when the two strings are equal.
This fee tool understands `total` and `max`. Try it: change the first argument from total to max, then to avg, and run again.
Total fees: Rs 3000
💡 Returning 1 from main tells the terminal that something went wrong; 0 means success.
🤔 Predict the output
Think like C: read the code and choose what it prints. You get the reason straight away.
Question 1. This fakes running `./greet Hello World`. What does it print?
char *argv[] = { "./greet", "Hello", "World" };
int argc = 3;
printf("%d %s\n", argc, argv[argc - 1]);Question 2. What does this print?
printf("%d\n", atoi("12abc") + atoi("abc"));Question 3. What does this print?
if (strcmp("-A", "-a") == 0) printf("same\n");
else printf("different\n");🧩 Your challenge
Write a railway ticket tool. The first argument is the fare per person, the rest are passenger names. Print each passenger with the fare, then the total. If fewer than 2 arguments are given, print a usage message. Example for arguments 450 Asha Ravi Meena: Asha - Rs 450 Ravi - Rs 450 Meena - Rs 450 Tickets: 3, Total: Rs 1350
Asha - Rs 450 Ravi - Rs 450 Meena - Rs 450 Tickets: 3, Total: Rs 1350
⚠️ Common mistakes (and how to fix them)
❌ Wrong
char *args[] = { "marks", "40", "35" };
int total = args[1] + args[2];
printf("%d\n", total);Line 2: error: invalid operands to binary expression ('char *' and 'char *')
✅ Right
char *args[] = { "marks", "40", "35" };
int total = atoi(args[1]) + atoi(args[2]);
printf("%d\n", total);Arguments are strings (char pointers), and C cannot add two pointers. Convert each one with atoi or strtol first.
❌ Wrong
const char *cmd = "add";
if (cmd == "add") printf("Adding\n");
else printf("Unknown\n");Line 2: warning: result of comparison against a string literal is unspecified (use an explicit string comparison function instead) [-Wstring-compare]
✅ Right
const char *cmd = "add";
if (strcmp(cmd, "add") == 0) printf("Adding\n");
else printf("Unknown\n");== compares the addresses of two strings, not their letters. With a real argv[1] it is almost always false. Clang warns you; use strcmp.
❌ Wrong
char *argv[] = { "./avg", "70", "80" };
int argc = 3;
printf("Numbers given: %d\n", argc);
(void)argv;Compiles and runs, but prints: Numbers given: 3 ⏎
✅ Right
char *argv[] = { "./avg", "70", "80" };
int argc = 3;
printf("Numbers given: %d\n", argc - 1);
(void)argv;argc also counts the program name in argv[0]. The number of real arguments is argc − 1.
📌 Remember
- main(int argc, char *argv[]) receives the words typed after the program name.
- argc counts all words including the program name; argv[0] is the program name.
- Arguments are always strings: convert with atoi, or strtol when you need to check for bad input.
- Compare argument words with strcmp, never with ==.
- Check argc first and print a usage message when the arguments are wrong.
Finished the quiz and the challenge?
Questions students ask
What does argv stand for in C?
argv means argument vector, an old word for array. It is an array of strings. argc is the argument count. You may give them other names, but everyone uses argc and argv.
Is it char *argv[] or char **argv?
Both mean the same thing as a parameter of main. An array parameter is really a pointer to its first element (Lesson 3), so char *argv[] becomes char **argv.
What is argv[argc]?
The C standard says argv[argc] is always a NULL pointer. That marks the end of the list. Never read argv[i] for i greater than argc.
How do I pass an argument with a space in it?
Put it in quotes in the terminal: ./greet "Riya Sharma". The shell then passes it as one argument, so argv[1] is "Riya Sharma".