问题描述
给出主程序的标准定义:
Given the standard definition for the main program:
int main(int argc, char *argv[]) {
...
}
在什么情况下POSIX系统上argc
可以为零?
Under which circumstances can argc
be zero on a POSIX system?
推荐答案
是的,有可能.如果您按以下方式调用程序:
Yes, it is possible. If you call your program as follows:
execl("./myprog", NULL, (char *)NULL);
或者:
char *args[] = { NULL };
execv("./myprog", args);
然后在"myprog"中,argc
将为0.
Then in "myprog", argc
will be 0.
标准也专门允许关于主机环境中程序启动的第5.1.2.2.1节中所述的0 argc
:
The standard also specifically allows for a 0 argc
as noted in section 5.1.2.2.1 regarding program startup in a hosted environment:
int main(void) { /* ... */ }
或具有两个参数(此处称为argc
和argv
,尽管可以使用任何名称,因为它们是本地名称 到声明它们的函数):
or with two parameters (referred to here as argc
and argv
, 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 如果已声明,则main
函数的参数应遵循以下约束:
2 If they are declared, the parameters to the main
function shall obey the following constraints:
-
argc
的值应为非负数. -
argv[argc]
应为空指针.
- The value of
argc
shall be nonnegative. argv[argc]
shall be a null pointer.
...
还请注意,这意味着如果argc
为0,则保证argv[0]
为NULL.但是,在标准中没有明确说明printf
在用作%s
说明符的参数时如何处理NULL指针.在这种情况下,许多实现都将输出(null)",但我不认为这是可以保证的.
Note also that this means that if argc
is 0 then argv[0]
is guaranteed to be NULL. How printf
treats a NULL pointer when used as the argument to a %s
specifier is not spelled out in the standard however. Many implementations will output "(null)" in this case but I don't believe it's guaranteed.
这篇关于在POSIX系统上argc可以为零吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!