Quiz Entry - updated: 2026.07.10
How do command line arguments work in C?
main(int argc, char *argv[]) gets the argument count in argc and the arguments themselves as an array of strings in argv, where argv[0] is the program name and argv[argc] is NULL.
* argv is an array of string pointers ending in NULL; argv[0] is the program name, so argc is always at least 1. *
int main(int argc, char *argv[])
{
// argc: number of arguments (always >= 1)
// argv: array of C strings (char pointers)
// argv[0]: program name
// argv[1..argc-1]: actual arguments
// argv[argc]: NULL (sentinel)
}
Example: Running ./program hello world
argc = 3
argv[0] = "./program"
argv[1] = "hello"
argv[2] = "world"
argv[3] = NULL
Iterating over arguments:
for (int i = 0; i < argc; i++) {
printf("argv[%d] = '%s'\n", i, argv[i]);
}
// Or using the NULL sentinel:
for (char **p = argv; *p != NULL; p++) {
printf("%s\n", *p);
}
Memory layout of argv:
argv → [ptr0][ptr1][ptr2][NULL]
↓ ↓ ↓
"./prog" "hello" "world"
Equivalent declarations:
// Array notation
int main(int argc, char *argv[]);
// Pointer notation (same thing!)
int main(int argc, char **argv);
Common patterns:
// Check for minimum arguments
if (argc < 2) {
fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
return 1;
}
// Convert argument to integer
// or better: strtol for error checking
int n = atoi(argv[1]);