typestar

Command-line arguments in C

argv[0] is the program name, and argv[argc] is always NULL.

#include <stdio.h>

int main(int argc, char **argv) {
    if (argc < 2) {
        fprintf(stderr, "usage: %s WORD...\n", argv[0]);
        return 1;
    }

    for (int i = 1; i < argc; i++) {
        printf("%d: %s\n", i, argv[i]);
    }

    printf("argv[argc] is NULL: %d\n", argv[argc] == NULL);
    return 0;
}

How it works

  1. argc counts the program name too, so options start at one.
  2. Every argument arrives as a NUL-terminated string.
  3. Returning non-zero from main signals failure to the shell.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
267
Tokens
93
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 59 seconds.

Type this snippet

Step 1 of 4 in Program environment, step 1 of 14 in Systems programming.

Next →