0
0
CHow-ToBeginner · 3 min read

How to Use Command Line Arguments in C: Simple Guide

In C, command line arguments are accessed using the main function parameters int argc and char *argv[]. argc counts the arguments, and argv is an array of strings holding each argument passed when running the program.
📐

Syntax

The main function can accept two parameters to handle command line arguments:

  • int argc: Counts how many arguments are passed, including the program name.
  • char *argv[]: An array of strings holding each argument as a text.

This allows your program to read inputs given when it starts from the command line.

c
int main(int argc, char *argv[]) {
    // Your code here
    return 0;
}
💻

Example

This example prints all command line arguments passed to the program, including the program name itself.

c
#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("Number of arguments: %d\n", argc);
    for (int i = 0; i < argc; i++) {
        printf("Argument %d: %s\n", i, argv[i]);
    }
    return 0;
}
Output
Number of arguments: 3 Argument 0: ./program Argument 1: hello Argument 2: world
⚠️

Common Pitfalls

Common mistakes when using command line arguments include:

  • Not checking if argc is enough before accessing argv elements, which can cause errors.
  • Assuming arguments are always valid strings without validation.
  • Confusing argv[0] as the first user argument; it is actually the program name.

Always check argc before using argv to avoid crashes.

c
#include <stdio.h>

int main(int argc, char *argv[]) {
    // Wrong: Accessing argv[1] without checking argc
    // printf("First argument: %s\n", argv[1]); // May crash if no argument

    // Right: Check argc first
    if (argc > 1) {
        printf("First argument: %s\n", argv[1]);
    } else {
        printf("No arguments provided.\n");
    }
    return 0;
}
Output
No arguments provided.
📊

Quick Reference

Remember these key points when using command line arguments in C:

  • argc is the count of arguments including the program name.
  • argv[0] is the program name.
  • argv[1] to argv[argc-1] are user arguments.
  • Always check argc before accessing argv elements.

Key Takeaways

Use int argc, char *argv[] in main to access command line arguments.
argc tells how many arguments were passed, including the program name.
argv holds each argument as a string, with argv[0] being the program name.
Always check argc before using argv to avoid errors.
Command line arguments let users give input to your program when it starts.