Command Line Arguments in C (argc and argv)
On this page (9sections)
Introduction
When you run a program from the terminal, the shell passes command line arguments. In C, main can receive them through argc (argument count) and argv (argument vector).
Syntax
int main(int argc, char *argv[])
| Parameter | Meaning |
|---|---|
argc | Number of arguments (including program name) |
argv[0] | Program name |
argv[1] … argv[argc-1] | User-supplied arguments |
argv[argc] | Always NULL |
Example Program
#include <stdio.h>
int main(int argc, char *argv[]) {
int i;
printf("Program name: %s\n", argv[0]);
printf("Total arguments: %d\n", argc - 1);
for (i = 1; i < argc; i++)
printf("Argument %d: %s\n", i, argv[i]);
return 0;
}
How to Run
./args Hello World 123
Sample Output
Program name: ./args
Total arguments: 3
Argument 1: Hello
Argument 2: World
Argument 3: 123
Converting String Arguments to Numbers
Use <stdlib.h>:
int value = atoi(argv[1]); /* string to int */
long lv = strtol(argv[1], NULL, 10);
double dv = atof(argv[1]);
Best Practices
- Always check
argcbefore readingargv[1]. - Validate user input —
atoireturns 0 on failure with no error indication; preferstrtol. - Quote arguments with spaces when passing from shell.
Common Mistakes
- Accessing
argv[1]when no arguments were passed (undefined behavior). - Forgetting that
argvelements are strings, not numbers. - Modifying
argvstrings on some platforms may be unsafe — treat as read-only.
Related Pages
Continue learning with these related tutorials and programs:
- C Tutorials — Browse all C Tutorials.
- C Introduction — Start here — what C is and why it matters.
- C History — More in c basics.
- C Specific Properties and Implementation — More in c basics.