Skip to main content

Command Line Arguments in C (argc and argv)

1 min read
Share:
On this page (9sections)

Introduction

When you run a program from the terminal, the shell passes command line arguments. In C, main can receive them through argc (argument count) and argv (argument vector).

Syntax

int main(int argc, char *argv[])
ParameterMeaning
argcNumber of arguments (including program name)
argv[0]Program name
argv[1]argv[argc-1]User-supplied arguments
argv[argc]Always NULL

Example Program

#include <stdio.h>

int main(int argc, char *argv[]) {
    int i;

    printf("Program name: %s\n", argv[0]);
    printf("Total arguments: %d\n", argc - 1);

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

    return 0;
}

How to Run

./args Hello World 123

Sample Output

Program name: ./args
Total arguments: 3
Argument 1: Hello
Argument 2: World
Argument 3: 123

Converting String Arguments to Numbers

Use <stdlib.h>:

int value = atoi(argv[1]);       /* string to int */
long lv = strtol(argv[1], NULL, 10);
double dv = atof(argv[1]);

Best Practices

  • Always check argc before reading argv[1].
  • Validate user input — atoi returns 0 on failure with no error indication; prefer strtol.
  • Quote arguments with spaces when passing from shell.

Common Mistakes

  • Accessing argv[1] when no arguments were passed (undefined behavior).
  • Forgetting that argv elements are strings, not numbers.
  • Modifying argv strings on some platforms may be unsafe — treat as read-only.

Continue learning with these related tutorials and programs:

Related Tutorials

Search tutorials