1
votes

So I have a string passed into main function: int main(int argc, char* argv[])

I understand argc (which is 2 in this case), but don't understand how I can read argv[] character by character? When I print argv[0] shouldn't that print the first character in the array of characters for that string?

Thanks

2
The values passed on the command line start with argv[1]. The first character of that would be argv[1][0]. - Retired Ninja
argv[] is an array of strings(null terminated character arrays). Thus argv[0] gives the first string. To get the first character of the first string use *argv[0] or argv[0][0]. - Abhishek Choubey

2 Answers

7
votes

sample

#include <stdio.h> 

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

One more example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[])
{
    if(argc != 2)
    {
        //argv[0] is name of executable
        printf("Usage: %s argument\n", argv[0]);
        exit(1);
    }
    else
    {
        int i;
        int length = strlen(argv[1]);
        for(i=0;i<length;i++)
        {
            printf("%c",argv[1][i]);
        }
        printf("\n");
        return 0;
    }
}