Skip to main content

Command Line Arguments in C (argc and argv)

1 min read Updated June 30, 2026
Share:
On this page (10sections)

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:

Frequently Asked Questions

What does this C program do?
It is a C example program that demonstrates Command Line Arguments in C (argc and argv), including the complete source code and the expected sample output.
How do I compile and run this C program?
Save the code in a `.c` file, compile it with `gcc filename.c -o program`, then run it with `./program` (or `program.exe` on Windows).
What concepts does this example use?
This example uses loops to iterate over data and arrays, illustrating a common pattern in C programming.

Related Tutorials

Search tutorials