In command line arguments in C we can specify the arguments vector as char *argv[]
or char **argv
i understand the first one which is an array of pointers to characters but what is the relationship between an array of pointers to characters and the second type which looks a pointer to pointer to character?
CodePudding user response:
The difference between char *argv[]
and char **argv
is that:
char *argv[]
is a array ofchar *
pointers.char **argv
is a pointer to another pointer which points to achar
.
char *argv[]
can be visualized like this:
p1 -> "hello"
p2 -> "world"
p3 -> "!"
// p1, p2 and p3 are
// pointers to strings
// they have type char *
_________________
| p1| p2 | p3 |
—————————————————
// argv looks like this
// it is an array of all the pointers
when referencing the name of the array argv
in an expression it will yield a pointer to the first element in the array.
The type of the array name argv
when used in an expression is char **
. This is because:
The array name
argv
decays to a pointer to the first element of the array.The first element also happens to be a pointer, so
argv
is essentially a pointer to another pointer hence the type ischar **
CodePudding user response:
Function parameters that are arrays get implicitly adjusted by the compiler into a pointer to the first item of that array.
In case of the array char* argv[]
, it's an array of char*
and a pointer to the first item is therefore a char**
. Therefore it doesn't matter if you type char* argv[]
or char**
, they are equivalent in this specific case.
Also since the char* []
will get adjusted to char**
, the size of the array doesn't matter. You could write char* argv [42]
and that would be equivalent as well.
Subjectively, char* argv[]
could be regarded as the most correct form, since it is 1) self-documenting - we are dealing with an array - and 2) the form used in the C standard 5.1.2.2.1 (hosted systems).