argc and argv
- C course
- Intermediate
- Lesson 88/116
- 4 min
Learn command-line arguments with argc and argv.
argc and argv
In C, command-line arguments reach the main function through two parameters: argc and argv. argc is an integer holding the argument count; argv is an array of string pointers, one per argument.
The first entry argv[0] is always the program name. Real user arguments start at argv[1]. For example, running ./prog apple pear gives argc 3; argv[1] is "apple", argv[2] is "pear". This lets you change the program's behavior at run time.
The main signature
To receive arguments you write main as int main(int argc, char *argv[]). Here argv is an array of char *; each element points to a string.
Parameter names are free; int main(int ac, char **av) also works. What matters is the type order: first int, then a char * array. Writing int main(void) means the program cannot access arguments. Most toolchains still place them in memory; the standard way is to declare the signature explicitly.
Practice Print the argc value
Write the signature int main(int argc, char *argv[]). Print argc with printf using the format "argc=%d\n". End with return 0.
Starter code
#include <stdio.h>
// Write main with argc and argv
// Print the argc value
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("argc=%d\n", argc);
return 0;
}Expected output
argc=1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does argc hold?
- The argument count Correct answer
- The address of the first argument
- The program return code
- The string length
Explanation: argc holds the number of command-line arguments.
2 Print the argc value
printf("argc=%d
", ____);
printf("argc=%d
", argc);
Explanation: argc is an integer; it prints with %d.
3 Match the argc/argv parts
| Term | Meaning |
|---|---|
argc |
Argument count |
argv[0] |
Program name |
argv[1] |
First user argument |
char *argv[] |
String pointer array |