What does: "char *argv[]" mean?

93 views Asked by At

I have this program:

#include <stdio.h>

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

    for (i=0; i < argc;i++) {
        printf("argv[%d] = %s\n", i, argv[i]);
    }


}

I am wondering about the argument char *argv[]. My first thought was that this was an array of character pointers? But then it should compile if we write: (char *argv)[]? But then I get the error meassage

testargs.c:3:20: error: expected declaration specifiers or '...' before '(' token
    3 | int main(int argc, (char *argv)[]) {

However it will compile and run correctly if I have char *(argv[]). But what is this actually in terms of pointers and arrays? Is it a character pointer to an array, or what is it?

2

There are 2 answers

0
Daniel Friedman On

This represents an array of pointers to char, in other words, strings. The way you recognize this is that the array syntax [] is demoted to a pointer, so this is the same as **char, a pointer to pointers of chars.

0
Owl On

It's an array of pointers to C strings (or char arrays). Where each string in the array is in the first[] and each character is in a second [], and each string of chars is an array of characters typically terminated by a null character or a zero byte.

In main() the argc parameter specifies how many strings there are in the char *arcv[] array.

The operating system when calling into main will specify the number of parameters, the int argc value as well as the command line parameters provided to main() in the char *argv[] parameter.

The first argv parameter is typically the program name itself, and this is followed by any additional parameters specified on the command line.

So for instance if you did:

./program.bin parameter1 --option1

And the data in it would be dereferenced like this:

puts(argv[0]) // would be "./program.bin"
puts(argv[1]) // would be "parameter1"
puts(argv[2]) // would be "--option1"

and argc would be 3.

The way i'd think of this is as char **argv, in fact you can replace char *argv[] as char **argv.

And I would think of this in the layout char *(argv[stringnum]) or char (argv[stringnum])[letternum] or just char argv[stringnum][letternum]

Now, the reason:

(char *argv)[]

doesn't work is, is because your declaration of the variable argv is embedded within some code to dereference it and the compiler is confused about whether it's a declaration or a function. In the error message it thinks it should be a declaration, but it doesn't understand the format. Instead use char *argv[] or char **argv