Command Line Arguments in C
So far, your programs got input with scanf after they started. But many programs take input when they start: you type gcc main.c -o app, and gcc receives "main.c", "-o" and "app". These are called command line arguments.
In this lesson you will learn how main receives them through argc and argv, how to turn them into numbers, how to check that the user gave the right number of values, and how to write small tools like a sum program and a calculator.
What You Will Learn
- What command line arguments are.
- The meaning of
argcandargv. - Why
argv[0]is the program name. - How to convert arguments to numbers with
atoi,atofandstrtol. - How to check the argument count and print a usage message.
- How to pass arguments in an IDE as well as in the terminal.
Command Line Arguments in C Explained
Exam definition: Command line arguments are values passed to a program when it is run from the command line. They are received by main through two parameters: int argc (argument count), the number of arguments including the program name, and char *argv[] (argument vector), an array of strings where argv[0] is the program name, argv[1] to argv[argc-1] are the arguments, and argv[argc] is NULL.
Memory trick: When you board a bus, the conductor writes a passenger list. argc = how many people are on the list (count). argv = the list of names (vector). The driver's name is always first (argv[0] = the program itself), and every value is written as text, even numbers.
Syntax of main with Arguments
int main(int argc, char *argv[]) /* most common form */
int main(int argc, char **argv) /* exactly the same meaning */
/* Running: ./prog apple 42 "New Delhi"
argc = 4
argv[0] = "./prog"
argv[1] = "apple"
argv[2] = "42" (a string, not the number 42)
argv[3] = "New Delhi" (quotes keep words together)
argv[4] = NULL */
The names argc and argv are only a convention, but every C programmer uses them.
Example 1: Printing All Arguments
Save the program as args.c, compile it and run it with three arguments:
gcc args.c -o args
./args Delhi 25 hello
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
printf("argc = %d\n", argc);
for (i = 0; i < argc; i++)
printf("argv[%d] = %s\n", i, argv[i]);
return 0;
}
Output
argc = 4 argv[0] = ./args argv[1] = Delhi argv[2] = 25 argv[3] = hello
Code Explanation
int main(int argc, char *argv[]): the operating system callsmainand fills these two parameters for us.argcis 4: the program name plus three arguments.argv[0]is the program name exactly as typed (./args). On Windows it may be the full path, likeC:\code\args.exe.argv[1],argv[2],argv[3]are the arguments. Notice"25"is printed with%s: it is a string.- The loop runs from 0 to
argc - 1. It must never read beyondargv[argc], which isNULL.
How Command Line Arguments Work
The shell splits what you type at spaces, stores each word as a string and gives main an array of pointers to them:
You type: ./args Delhi 25 hello
argv ──► [0] ──► "./args"
[1] ──► "Delhi"
[2] ──► "25"
[3] ──► "hello"
[4] ──► NULL
argc = 4
- To pass a value containing spaces, use quotes:
./args "New Delhi"gives one argument. - Numbers arrive as text. Convert them:
atoi(argv[1])for int,atof(argv[1])for double, orstrtolwhen you need error checking. - In Code::Blocks use Project → Set programs' arguments; in VS Code, add them to the run command in the terminal.
Example 2: Sum and Average of Numbers from the Command Line
./sum 10 20 30.5
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i;
double total = 0;
if (argc < 2)
{
printf("Usage: %s num1 num2 ...\n", argv[0]);
return 1;
}
for (i = 1; i < argc; i++)
total += atof(argv[i]);
printf("Numbers given: %d\n", argc - 1);
printf("Sum = %.2f\n", total);
printf("Average = %.2f\n", total / (argc - 1));
return 0;
}
Output
Numbers given: 3 Sum = 60.50 Average = 20.17
- The loop starts at 1, because
argv[0]is the program name, not a number. atofconverts "30.5" into the double 30.5.- If the user runs
./sumwith no numbers, the program prints a usage message and returns 1 (a non-zero exit code means "failed"). Always checkargcbefore usingargv[1].
Important Points to Remember
argc= number of arguments including the program name, so it is always at least 1.argv[0]= program name; real arguments start atargv[1].- Every argument is a string; convert numbers with
atoi,atoforstrtol. argv[argc]is alwaysNULL.- Check
argcfirst and print a usage message if values are missing. - Arguments are separated by spaces; use quotes for values with spaces.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
Using argv[1] without checking argc | Crash when no argument is given | if (argc < 2) { usage; return 1; } |
int n = argv[1]; | Stores a pointer, not the number | int n = atoi(argv[1]); |
| Loop starting at 0 when adding numbers | Tries to convert the program name | Start the loop at 1 |
if (argv[1] == "add") | Compares addresses, always false | strcmp(argv[1], "add") == 0 |
| Thinking argc counts only the arguments | Off-by-one errors | Remember argc includes argv[0] |
Command Line Arguments Practice Questions
- What are argc and argv? What are their types?
- What is the value of argc for
./app one two? - What does
argv[0]contain? - Why must arguments be converted before arithmetic?
- How do you pass "Hello World" as a single argument?
Show answers
- argc (
int) is the number of arguments including the program name; argv (char *[]) is an array of strings holding them. - 3.
- The program name (as typed, or the full path on some systems).
- Because every argument is a string;
"25"is text, so it must be converted with atoi/atof/strtol. - Put it in quotes:
./app "Hello World".
Coding Exercise
Write calc.c that is run as ./calc 12 x 5 and prints the result. Support +, -, x (multiply, because * means "all files" to the shell) and /. Print a usage message if there aren't exactly 3 arguments.
Show solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
double a, b, result;
if (argc != 4)
{
printf("Usage: %s number op number (op: + - x /)\n", argv[0]);
return 1;
}
a = atof(argv[1]);
b = atof(argv[3]);
if (strcmp(argv[2], "+") == 0) result = a + b;
else if (strcmp(argv[2], "-") == 0) result = a - b;
else if (strcmp(argv[2], "x") == 0) result = a * b;
else if (strcmp(argv[2], "/") == 0)
{
if (b == 0) { printf("Error: division by zero\n"); return 1; }
result = a / b;
}
else
{
printf("Unknown operator: %s\n", argv[2]);
return 1;
}
printf("%s %s %s = %g\n", argv[1], argv[2], argv[3], result);
return 0;
}
12 x 5 = 60
Quick Quiz: Command Line Arguments (MCQ)
-
For
./prog a b c, argc is:A) 3 B) 4 C) 2 D) 5
-
The type of
argvis:A)
int[]B)charC)char *[]D)float * -
argv[0]holds:A) The first argument B) The program name C) NULL D) argc
-
Which function converts "45" to the integer 45?
A)
atoiB)itoaC)strlenD)printf -
argv[argc]is:A) The last argument B) Garbage C) NULL D) The program name
Show answers
- B: 4.
- C:
char *[]. - B: the program name.
- A:
atoi. - C: NULL.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Signature | int main(int argc, char *argv[]) |
|---|---|
| argc | Argument count, includes the program name |
| argv | Argument vector: array of strings |
| argv[0] | Program name |
| argv[argc] | NULL |
| Numbers | Arrive as strings: use atoi / atof / strtol |
| Spaces in a value | Wrap it in quotes |
Frequently asked questions
- What are command line arguments in C?
- Values given to a program when it starts, received by main as argc (count) and argv (array of strings).
- Why is argc at least 1?
- Because argv[0] always holds the program name.
- How do you use a numeric command line argument?
- Convert the string with atoi(), atof() or strtol() before doing arithmetic.
Remember
- argc = count, argv = list; the driver (program name) comes first.
- Check argc before touching argv[1].
Next Topic
Next lesson: Variadic Functions in C. You will write functions like printf that accept any number of arguments using stdarg.h.