Course contentsShow
← C
Lesson 506 of 1,2197. PointersFree lesson

Command line arguments `char **argv`

Command line arguments char **argv

What you'll learn: How to use pointers to pointers to access the text strings passed into your program when it starts.

Up until now, you have likely seen int main() or int main(void). However, C allows your program to receive "input" the very moment it is launched. This is handled through two special parameters: int argc (the count) and char **argv (the arguments).

The Post Office Analogy

Imagine you are a clerk at a post office. A customer drops off a large box labeled argv.

Inside that box isn't the actual mail. Instead, the box contains a row of envelopes. Each envelope has a memory address written on it (that’s the first pointer). When you open an envelope and follow that address, you find a sticky note with a word written on it (that’s the second pointer, leading to a character).

Because argv is a pointer to a pointer, it represents a list of addresses that point to the start of various strings (words) stored in memory.

Seeing it in code

When you run a command like ./myprog hello world, the operating system gathers those words and hands them to your program.

#include <stdio.h>

int main(int argc, char **argv) {
    // argc is the number of arguments (including the program name)
    printf("You provided %d arguments.\n", argc);

    // argv[0] is always the name of the program itself
    // argv[1], argv[2], etc., are the words that follow
    for (int i = 0; i < argc; i++) {
        printf("Argument %d is: %s\n", i, argv[i]);
    }

    return 0;
}

Why the double asterisk?

You know that a char * is a string (a pointer to the first character). Since we need a list of strings, we need a pointer to the first char *.

Think of it as a hierarchy:

  1. argv points to the beginning of an array.
  2. Each element in that array is a char *.
  3. Each char * points to the actual letters ('h', 'e', 'l', 'l', 'o') in memory.

By using char **argv, C gives you a flexible way to handle any number of words of any length without knowing how many there will be until the program actually starts.

Key takeaway

char **argv is a pointer to an array of pointers, where each pointer leads to a string representing a command-line input.