Alex Rivera | Logout

Pointer to Pointer with argv

Asked 2011-10-03T05:23:35.700
32

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:

  1. Take argv, dereference it.
  2. It should return the address of the array of pointers to characters.
  3. Using pointer arithmetics to access elements of the array.
c
Edit
Report

1 Answer

22

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.

answered 2011-10-03T16:46:13.680

Your Answer