-4

I found this code from book named "Learn C the hard way", but I am could not understand the meaning and purpose of :

for(i=0;argv[1][i]!='\0';i++){
    char letter=argv[1][i];
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Pratik Parmar
  • 321
  • 3
  • 12

3 Answers3

3

main with parameters according to the C Standard is declared like

int main( int argc, char * argv[] )

that is equivalent to

int main( int argc, char ** argv )

that is argv points to first element of an array of pointers to first characters of strings.

Thus argv[1] is pointer to first character of the second parameter (the first parameter is the program name). For example *argv[1] or argv[1][0] is the first character of a zero-terminated string.

For example if your program is run like

your_program Hello

then the command line parameter is passed to the program like string "Hello". And this loop

for(i=0;argv[1][i]!='\0';i++){
    char letter=argv[1][i];

traverses the string until the terminating zero is encountered.

You can output all parameters character by character the following way

#include <stdio.h>

int main( int argc, char * argv[] ) 
{
    for ( int i = 0; i < argc; i++ )
    {
        for ( int j = 0; argv[i][j] != '\0'; j++ ) putchar( argv[i][j] );
        printf( "\n" );
    }

    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

argv[1] is the second string in the string array argv, and strings are character arrays so argv[1][0] is the first character in the second string, argv[1][1] is the second character in the second string and so on.

msc
  • 33,420
  • 29
  • 119
  • 214
-1

For each letter in the argument passed to the program it creates a variable called letter with that value.
I think it is used in the following rows of the for cycle.

Wallkan
  • 480
  • 1
  • 8
  • 27