2

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
  • 1
    The values passed on the command line start with argv[1]. The first character of that would be argv[1][0]. Commented Sep 27, 2014 at 7:22
  • 1
    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]. Commented Sep 27, 2014 at 8:18

2 Answers 2

7

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, I swear I tried the same thing but it didn't work. Does ++i vs i++ make any difference? I couldn't understand other people's explanations.
Please share the code that didn't work. No, in this context the pre or post increment operator makes no difference. It does make a difference if it is part of an expression being assigned or evaluated, as opposed to an increment operation alone.
@aNobody You should post together the code that did not work well when you asked question.
@aNobody Does ++i vs i++ make any difference? : There is no much difference if it's running alone.
@aNobody ++i is more efficient by a very tiny amount because the additional storage for the return value need not be allocated.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.