I am trying to understand the pointer used in line of code below written by the user H.S in this post. Could anyone help me?
for (char **pargv = argv+1; *pargv != argv[argc]; pargv++)
The whole code:
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("ERROR: You need at least one argument.\n");
return -1;
}
for (char **pargv = argv+1; *pargv != argv[argc]; pargv++) {
/* Explaination:
* Initialization -
* char **pargv = argv+1; --> pargv pointer pointing second element of argv
* The first element of argument vector is program name
* Condition -
* *pargv != argv[argc]; --> *pargv iterate to argv array
* argv[argc] represents NULL
* So, the condition is *pargv != NULL
* This condition (*pargv != argv[argc]) is for your understanding
* If using only *pragv is also okay
* Loop iterator increment -
* pargv++
*/
printf ("Vowels in string \"%s\" : ", *pargv);
for (char *ptr = *pargv; *ptr != '\0'; ptr++) {
if (*ptr == 'a' || *ptr == 'e' || *ptr == 'i' || *ptr == 'o' || *ptr == 'u'
|| *ptr == 'A' || *ptr == 'E' || *ptr == 'I' || *ptr == 'O' || *ptr == 'U') {
printf ("%c ", *ptr);
}
}
printf ("\n");
}
return 0;
}
Questions:
The two dereference operators used in the first
**pargv = argv+1
are used because the argv is an array of pointers, therefore it is necessary to use a pointer to a pointer (**pargv) to refer to it. Is this statement correct?Why is it necessary to point to the address of the argv
(argv+1)
or(&argv[1])
and not the value (*argv[1]) that is inside it?
In my mind pointing to the address would bring the int number of the address, but I know the code is correct this way. So why pointing to the address return the value inside?
I have tried to change the piece of code below by replacing the argv+1
for argv[1]
because in my mind I should point to the value inside of the array and not to the address that leads to the value but I got an error from the compiler (GCC).
for (char **pargv = argv+1; *pargv != argv[argc]; pargv++)