C ยท Chapter 40 of 45

C Command Line Arguments

C programs can receive input directly when they're launched, via command line arguments. These are captured through main()'s optional parameters: argc (argument count) and argv (argument values).

argv[0] is always the program's own name, and subsequent elements argv[1], argv[2], etc., are the arguments the user typed after the program name.

Syntax
int main(int argc, char *argv[]) { ... }

argc and argv

argc holds the total number of arguments (including the program name). argv is an array of C strings, one per argument, with argv[argc] guaranteed to be NULL.

Using arguments

Since argv elements are strings, numeric arguments must be converted using functions like atoi() or strtol() before being used in calculations.

Example 1 (c)
#include <stdio.h>

int main(int argc, char *argv[]) {
  printf("Program: %s\n", argv[0]);
  printf("Arg count: %d\n", argc);
  return 0;
}
Output
Program: ./myapp
Arg count: 1

Run as `./myapp` with no extra arguments, argc is 1 and argv[0] is the program name.

Example 2 (c)
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
  if (argc > 1) {
    int n = atoi(argv[1]);
    printf("Doubled: %d\n", n * 2);
  }
  return 0;
}
Output
Doubled: 10

Running `./myapp 5` converts argv[1] ("5") to an int with atoi, then doubles it.

Key points

  • argc counts the arguments; argv holds them as an array of strings.
  • argv[0] is always the program's own name.
  • Use atoi()/strtol() to convert string arguments into numbers.
  • argv[argc] is guaranteed to be a NULL pointer.
๐Ÿ’ก Note: Always check argc before accessing argv indexes to avoid reading past the array's valid arguments.

๐Ÿ“ Quick Quiz

1. What does argv[0] represent?

2. What type is each element of argv?

3. Which function converts a string argument to an int?