I am learning C programming, I wrote the sample code to accept parameters from terminal and print out the arguments.
I invoke the program like this: ./myprogram 1
I expected 1 to be printed out for the argument length instead of 2. why it is so? There was no spacing after the argument "1"
#开发者_StackOverflow中文版include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
printf("%d", argc);
return EXIT_SUCCESS;
}
The first argument, argv[0]
is the name with which the program was invoked. So there are two arguments and the second, argv[1]
is "1".
EDIT
Editing to make clear: argc
should always be checked. However uncommon, it is perfectly legal for argc
to be 0.
For example on Unix, execvp("./try", (char **){NULL});
is legal.
"./myprogram" counts as the first argument.
精彩评论