Using pointers to iterate through argv[]
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.
Since for
loop allows any kind of values, not necessarily integers for your "loop index", your loop could be rewritten like this:
for (char **a = argv ; a != argv+argc ; a++) {
for(char *p = *a ; *p != '\0' ; p++) {
// code uses *p instead of argv[i][j]
}
}
The inner loop uses p
as the loop variable, which is incremented with the regular p++
, and checked with *p != '\0'
. The loop condition could be shortened to *p
, so the inner loop would look like this:
for(char *p = *a ; *p ; p++)
Yes you can iterate through argv
using pointers.
The inner loop tells p
to point at the beginning of argv+i
and iterate through it until it reaches \0
.
#include <stdio.h>
int main(int argc, char **argv) {
int i;
char *p;
for(i=0; i < argc; i++) {
for(p=*(argv+i); *p; p++)
printf("%c", *p);
printf("\n");
}
}
If you are only interested in traversing the each arguments, but not interested in parsing each character, then you can simply.
#include <stdio.h>
int main(int argc, char **argv) {
int i;
char *p;
for(i=0; i < argc; i++) {
printf("Argument position %d is %s\n", i, *(argv+i));
}
}