Steven Smarty Steven Smarty - 3 months ago 10
C Question

meaning of this code :for(i=0;argv[1][i]!='\0';i++)

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];

Answer

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;
}