0
0
CHow-ToBeginner · 3 min read

How to Pass Arguments to Main Function in C: Syntax and Example

In C, you can pass arguments to the main function by defining it as int main(int argc, char *argv[]). Here, argc counts the arguments, and argv is an array of strings holding each argument passed from the command line.
📐

Syntax

The main function can accept two parameters:

  • int argc: The number of command-line arguments, including the program name.
  • char *argv[]: An array of strings representing each argument.

This allows your program to receive input from the command line when it starts.

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 arguments in main include:

  • Forgetting that argv[0] is the program name, not the first user argument.
  • Accessing argv elements without checking argc, which can cause errors.
  • Using char **argv or char *argv[] interchangeably without understanding they mean the same.

Always check argc before accessing argv elements to avoid out-of-bounds errors.

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

/* Right way: Check argc before access */
int main(int argc, char *argv[]) {
    if (argc > 1) {
        printf("First argument: %s\n", argv[1]);
    } else {
        printf("No arguments passed.\n");
    }
    return 0;
}
📊

Quick Reference

Remember these key points when passing arguments to main:

  • argc is the count of arguments including the program name.
  • argv is an array of strings holding each argument.
  • argv[0] is always the program name.
  • Check argc before accessing argv elements.

Key Takeaways

Define main as int main(int argc, char *argv[]) to receive command-line arguments.
argc tells how many arguments were passed, including the program name.
argv is an array of strings holding each argument; argv[0] is the program name.
Always check argc before accessing argv elements to avoid errors.
Use argv to customize program behavior based on user input from the command line.