Using pointers to iterate through argv[]

Blake Lassiter picture Blake Lassiter · Jun 24, 2015 · Viewed 11.6k times · Source

I want to use the following code, but without indexing the array with"[][]" and substitute it with pointers

for (int i = 0; i < argc; i++) {
    for (int j = 0; argv[i][j] != '\0'; j++) {
        //code
    }
}

I know that you can use pointers to traverse an array, but I'm unsure how to do that with an undefined length in the second array, in this case the string from input. Since each element of argv[] can have a different length, I want to make sure that I can properly read the characters and know when each element of argv[] ends, and the next begins.

I expect it to be something like: (If the following header to main is wrong, please tell me.)

int main(int argc, char **argv) {
    for (int i = 0; i < argc; i++) {
        while(argv != '\0') {
            //code
            *argv+1;
        }
        //to skip null character
        argv+1;
    }
}

Answer

Ryan Haining picture Ryan Haining · Jun 24, 2015

Given that the last element in argv is NULL, you don't need to index it or compare anything with argc if you really don't want to.

int main(int argc, char *argv[]) {
  for (char **arg = argv; *arg; ++arg) { // for each arg
    for (char *p = *arg; *p; ++p) {      // for each character
      process(*p);
    }
  }
}

*arg will be NULL at the end of the list of arguments, which is false. *p will be '\0' at the end of each string, which is false.

From N1256 5.1.2.2.1/2

If they are declared, the parameters to the main function shall obey the following constraints:

— The value of argc shall be nonnegative.

— argv[argc] shall be a null pointer.