How to print argv arguments from main function in C?

Viewed 89323

So I just learnt that we can give two arguments into main function namely "argc" and "argv. However I am not able to understand what argv is in this: int main(int argc, char* argv[]);

Is argv an array of characters? or is it an array of pointers pointing to characters? Either way I am looking for a way to print out the arguments that the user passes to this program. This is the code the I wrote, but it's not printing the argv's so to speak. What's wrong in it? I guess it's my understanding of argv that's making this code incorrect.

#include<stdio.h>
int main(int argc, char *argv[])
{
    int i;
    printf("%d\n",argc);
    for(i=0;i<argc-1;i++)
    {
        printf("%s",*argv[i]);
    }
    return 0;
}

After the suggestions that I got from answers, I corrected my code as follows.

#include<stdio.h>
int main(int argc, char *argv[])
{
    int i;
    printf("%d\n",argc);
    for(i=1;i<argc;i++)
    {
        printf("%s",argv[i]);
    }
    return 0;
}

And I am using Ubuntu Linux in VMWare on my windows 8.1 pc. This is the output that I am getting. It's just printing argc and after that nothing. What's the problem? Is it the way I am compiling it or something in Linux terminal?

The snapshot of my terminal

In the above figure, I want the numbers 2,4,5,3 to be printed again, but they are not getting printed.

Thanks.

7 Answers

argv is a NULL terminated array of strings. So one doesn't even need argc to print all the arguments passed to the main function. So if argv points to NULL then that's the end of the arguments passed.

So to sum it up, you can do this with a simple while loop, using only argv:

    while (*argv != NULL)
    {
            printf("%s\n", *argv);
            argv++;
    }
Related