给定主程序的标准定义:
int main(int argc, char *argv[]) {
...
}
在 POSIX 系统上什么情况下 argc
可以为零?
最佳答案
是的,这是可能的。如果你调用你的程序如下:
execl("./myprog", NULL, (char *)NULL);
或者:
char *args[] = { NULL };
execv("./myprog", args);
然后在“myprog”中,argc
将为 0。
The standard还特别允许 0 argc
,如第 5.1.2.2.1 节中关于托管环境中的程序启动所述:
1 The function called at program startup is named
main
. The implementation declares no prototype for this function. It shall be defined with a return type ofint
and with no parameters:int main(void) { /* ... */ }
or with two parameters (referred to here as
argc
andargv
, though any names may be used, as they are local to the function in which they are declared):int main(int argc, char *argv[]) { /* ... */ }
or equivalent; or in some other implementation-defined manner.
2 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....
另请注意,这意味着如果 argc
为 0,则 argv[0]
保证为 NULL。然而,标准中并未详细说明 printf
在用作 %s
说明符的参数时如何处理 NULL 指针。在这种情况下,许多实现会输出“(null)”,但不能保证。
关于argc 在 POSIX 系统上可以为零吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49817316/