Search code examples
carraysstringargvdouble-pointer

argv function and string as address in C language


Question. How come the strings such as "C Programming" is compiled as address values as following?

 #include <stdio.h>

 void ShowAllString(int argc, char * argv[]) 
 {
     int i;
     for(i=0; i<argc; i++)
        printf("%s \n", argv[i]);
 }

 int main(void)
 {
     char * str[3]={
         "C Programming",
         "C++ Programming",
         "JAVA Programming"  };

    ShowAllString(3, str);
    return 0;
  }

My analogy was like the following... please correct me if you can.

char * argv[] if in parameter, that is equivalent to char ** argv . So the function is like void ShowAllString(int argc, char ** argv) to receive double pointer as argument. So it makes sense to have str as parameter because str is the name of the array char * str[3] and str is double pointer here as array name. char * str[3] is an array that is supposed to have three elements of pointers.... but how come such strings instead of address values are placed next to char * str[3]... this is where I am stuck!

Please help me!


Solution

  • In C, char[] is a pointer to where an array of char are stored, one after another in memory. As it happens, this is a good way to store a string. In your code, you are creating an array of 3 pointers to arrays of char. The first of which, str[0], points to where the sequence of char "C Programming" is stored in memory, and so on.

    (In everyday English one would generally call "a sequence of char" a "string", but technically, as the first comment correctly points out, this implies that char[] must by definition mean a string, which it doesn't.)

    You pass a pointer to this array of pointers to the function, which then retrieves the pointers to each of the arrays of char ("strings"), which the printf line uses to get the strings (arrays of char) and print them.