Search code examples
arrayscpointersc-stringspointer-arithmetic

Why do I have to use a two-dimensional array?


I'm reviewing this code which converts the capital letters to lower case and I don't understand why it declares char*argv[] and later inside the for loop it uses argv[1][i] as if it were a two-dimensional array. Any tip is welcomed, thanks.


#include <stdio.h>

int main(int argc, char*argv[]){
    if(argc>1) {
        int i;
        char c;
        for(i=1; (c=argv[1][i]) != '\0'; i++){
            if('A'<=c && c<='Z')
                putchar(c+'a'-'A');
            else
                putchar(c);
        }
        putchar('\n');
    }
}

Solution

  • argv is not actually a 2 dimensional array but an array of char *. Each of those pointers point to a string, each of which is a char array, so it can be accessed the same way a 2 dimensional array is.

    More specifically, each member of argv is a command line argument passed to the program, with the first member conventionally being the name of the program. Those arguments are strings, and each string is an array of characters. So argv[1][i] grabs the ith character from the first command line argument.