[英]Ubuntu passing command line arugments to C program
I am learning C programming, I wrote the sample code to accept parameters from terminal and print out the arguments. 我正在学习C编程,我编写了示例代码来接受来自终端的参数并打印出参数。
I invoke the program like this: ./myprogram 1 我这样调用程序:./myprogram 1
I expected 1 to be printed out for the argument length instead of 2. why it is so? 我希望打印出1作为参数长度,而不是2。为什么是这样? There was no spacing after the argument "1"
参数“ 1”后没有空格
#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. 第一个参数
argv[0]
是调用程序的名称。 So there are two arguments and the second, argv[1]
is "1". 因此,有两个参数,第二个参数
argv[1]
为“ 1”。
Editing to make clear: argc
should always be checked. 编辑清楚:应始终检查
argc
。 However uncommon, it is perfectly legal for argc
to be 0. 不管
argc
罕见, argc
为0完全合法。
For example on Unix, execvp("./try", (char **){NULL});
例如在Unix上,
execvp("./try", (char **){NULL});
is legal. 是合法的。
“ ./myprogram”被视为第一个参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.