输入参数是什么_

What Does Input Arguments is _

我想知道为什么结果 1 没有参数。

int main(int argcount, char *arglist[]) {
    int i;
    printf("Number of arguments %d\n",argcount);
    printf("Arguments list:\n");
    for (int i=0;i<argcount;i++)
        printf("%s\n",arglist[i]);
    return EXIT_SUCCESS;
}

./a.out 是第一个参数,因此 argcount 等于 1.

来自 C 标准(5.1.2.2.1 程序启动。p.#2)

— If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment.

因此,您使用的环境在第一个参数中提供了程序名称。

来自标准 (C11),特别注意粗体部分:

If they are declared, the parameters to the main function shall obey the following constraints:

  • The value of argc shall be nonnegative.
  • argv[argc] shall be a null pointer.
  • If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the hosted environment. If the host environment is not capable of supplying strings with letters in both uppercase and lowercase, the implementation shall ensure that the strings are received in lowercase.
  • If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment. If the value of argc is greater than one, the strings pointed to by argv[1] through argv[argc-1] represent the program parameters.
  • The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination.

换句话说,argc 包括表示程序名称的参数 - 程序的实际参数从 argv[1] 开始。根据以下记录,从程序输出中可以明显看出这一点,其中第一个参数是程序名称:

pax> cat testprog.c
#include <stdio.h>
int main(int argc, char *argv[]) {
    printf("Argument count: %d\n", argc);
    printf("Arguments:\n");
    for (int i = 0; i < argc; i++)
        printf("   %s\n", argv[i]);
    return 0;
}

pax> gcc --std=c11 -o testprog testprog.c && ./testprog 1 2 3
Argument count: 4
Arguments:
   ./testprog
   1
   2
   3

pax> ./testprog
Argument count: 1
Arguments:
   ./testprog