Based on my understanding of pointer to pointer to an array of characters,
% ./pointer one two argv +----+ +----+ | . | ---> | . | ---> "./pointer\0" +----+ +----+ | . | ---> "one\0" +----+ | . | ---> "two\0" +----+
From the code:
int main(int argc, char **argv) { printf("Value of argv[1]: %s", argv[1]); }
My question is, Why is argv[1] acceptable? Why is it not something like (*argv)[1]?
My understanding steps:
Because argv is a pointer to pointer to char , it follows that argv[1] is a pointer to char . The printf() format %s expects a pointer to char argument and prints the null-terminated array of characters that the argument points to.
The second parameter, argv (argument vector), is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
The second argument to main, usually called argv, is an array of strings. A string is just an array of characters, so argv is an array of arrays. There are standard C functions that manipulate strings, so it's not too important to understand the details of argv, as long as you see a few examples of using it.
The argv parameter is an array of pointers to string that contains the parameters entered when the program was invoked at the UNIX command line. The argc integer contains a count of the number of parameters. This particular piece of code types out the command line parameters.
It's more convenient to think of []
as an operator for pointers rather than arrays; it's used with both, but since arrays decay to pointers array indexing still makes sense if it's looked at this way. So essentially it offsets, then dereferences, a pointer.
So with argv[1]
, what you've really got is *(argv + 1)
expressed with more convenient syntax. This gives you the second char *
in the block of memory pointed at by argv
, since char *
is the type argv
points to, and [1]
offsets argv
by sizeof(char *)
bytes then dereferences the result.
(*argv)[1]
would dereference argv
first with *
to get the first pointer to char
, then offset that by 1 * sizeof(char)
bytes, then dereferences that to get a char
. This gives the second character in the first string of the group of strings pointed at by argv
, which is obviously not the same thing as argv[1]
.
So think of an indexed array variable as a pointer being operated on by an "offset then dereference a pointer" operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With