Skip to content
  • Command-Line Arguments · C

Command-Line Arguments

LearnViaNotes @learnvianotes· 2 min read

main(int argc, char *argv[]) receives the words typed after the program name: argc counts them, argv holds them as strings, and argv[argc] is always NULL.

C — run as: ./prog input.txt --verbose 42
#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("argc = %d\n", argc);
    for (int i = 0; i < argc; i++)
        printf("argv[%d] = \"%s\"\n", i, argv[i]);
    printf("argv[argc] is %s\n", argv[argc] == NULL ? "NULL" : "not NULL");
    return 0;
}
Output
argc = 4
argv[0] = "./prog"
argv[1] = "input.txt"
argv[2] = "--verbose"
argv[3] = "42"
argv[argc] is NULL

Converting and validating

C — run as: ./prog 10 20 x7 -5
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int parse_int(const char *s, long *out) {
    char *end;
    errno = 0;
    long v = strtol(s, &end, 10);
    if (end == s || *end != '\0' || errno == ERANGE) return -1;
    *out = v;
    return 0;
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        fprintf(stderr, "usage: %s NUM...\n", argv[0]);
        return EXIT_FAILURE;
    }
    long sum = 0;
    for (int i = 1; i < argc; i++) {
        long v;
        if (parse_int(argv[i], &v) != 0) { printf("skipping '%s'\n", argv[i]); continue; }
        sum += v;
    }
    printf("sum = %ld\n", sum);
    return EXIT_SUCCESS;
}
Output
skipping 'x7'
sum = 25

Parsing options

C — run as: ./prog -n 2 -v C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv) {
    int verbose = 0, count = 1;
    const char *name = "world";
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-v") == 0) verbose = 1;
        else if (strcmp(argv[i], "-n") == 0 && i + 1 < argc) count = atoi(argv[++i]);
        else name = argv[i];
    }
    for (int i = 0; i < count; i++) printf("hello, %s\n", name);
    if (verbose) printf("(printed %d times)\n", count);
    return 0;
}
Output
hello, C
hello, C
(printed 2 times)
  • argv[0] is the program name as invoked — it may be a path, or anything the parent process chose.

  • The shell does quoting and globbing: ./prog "a b" *.c passes a b as one argument and expands *.c before your program starts.

  • The strings in argv are modifiable and live until the program ends.

  • Environment variables: getenv("HOME") from <stdlib.h>.

What is argv[argc]?

Why is argv declared as char *argv[] and char **argv interchangeably?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report