这个 C 代码的输出是什么(运行 没有任何命令行参数)?

What is the output of this C code (run without any command line arguments)?

这段 C 代码的输出是什么(运行 没有任何命令行参数)?

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

在这个程序中argv给出了char指针数组的基址所以

while(*argv !=NULL) 

条件为真,这应该给出编译时错误,因为 *(argv++),不是吗?但它显示了一些输出,为什么?

无耻地引用 C11 规范第 §5.1.2.2.1 章,(强调我的

— The value of argc shall be non-negative.

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.

上面的代码片段只是打印提供的 程序参数。

  • *argv != NULL是为了检查我们没有到达argv数组的末尾。
  • printf("%s\n", *(argv++)); ,我们分解一下,

    printf("%s\n", *argv));  //print the string pointed to by `argv`
    argv++;                  //increment argv to point to the next string 
    

现在,进入 "title"

中的问题

[...] (run without any command line arguments)?

好吧,在这种情况下,argc 的值为 1,并且只有 argv[0] 持有指向包含程序名称的字符串的指针。 argv[1] 指向 NULL (或类似的空指针)。

所以,在循环中

  • 第一个条件检查成功(*argv == argv[0] 不为 NULL),它打印程序名称
  • argv 作为 post 增量的副作用而增加。
  • 第二次迭代,*argv现在和argv[1]一样,都是NULL,条件为假,命中最后的return语句。

正文中的问题

this should give the compile time error because of *(argv++), is not it?

不,不是。引用章节 §6.7.6.3

A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation. [...]

因此,argv 是一个可修改的左值,可以用作此处 post 固定增量运算符的操作数。