简体   繁体   中英

Command line argument passing

#include<stdio.h>

int main(int number, char arg[])
{
    int i;

    printf("%d\n",number);

    for(i=0;i<7;i++)
        printf("%c",arg[i]);
    printf("\n");   

    return 0;
}

I am running it in ubuntu terminal and running it by typing "./a.out".I expected the output to be "./a.out" but instead some garbage value is getting printed . Please explain why?

Your signature for main() is wrong:

int main(int number, char arg[])

should be:

int main(int number, char *arg[])

Then access it like a 2d array while printing, like:

for(i=0;i<strlen(argv[0]);i++)
    printf("%c",arg[0][i]);

Or just print the string at index 0:

printf("%s",arg[0]);

Because you're missing the type of argv . The OS pre-parses the arguments for you (separates them by spaces), so you'll end up having an array of strings. You should write:

int main(int argc, char **argv)
{
    int i;
    for (i = 0; i < argc; i++) {
        printf("%s ", argv[i]);
    }

    return 0;
}

in order to get the whole command line invocation back.

P. s.: you should really name the arguments of main() argc and argv. It's idiomatic and not doing so is strange.

main的签名是int main (int argc, char* argv[]) -即argv是一个字符串数组,而不是chars数组。

the main function, by convention takes an int as first parameter (this is ok in your code), but the second parameter has to be a pointer on an array of chars ( char *argv[] ).

This has to be so because when your program is called, it has its paremeter whithin this array. If you call ./a.out foo bar , the array will be

arg[0] = "./a.out"
arg[1] = "foo"
arg[2] = "bar"

and the integer will contain 3, the number of arguments given to your program.

If you wanted to print the number of argument given to your program and its arguments, you would need to transform your code to this

int main(int number, char *arg[]) // the right main prototype
{
    int i;

    printf("%d\n",number);

    for(i=0;i<number;i++) // from i = 0 to the number of parameters
        printf("%s\n",arg[i]); // print a string (%s)

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM