关于main函数的命令行参数
它看起来像 int main(int argc, char *argv[]); 。我的问题是:
1 我可以在 argv[]
中添加多少个数组项?
2 每个char *
的最大大小是多少?
It will look like int main(int argc, char *argv[]);
. My questions are:
1 How many array items can I add in argv[]
?
2 What is MAX size of every char *
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以尝试:
http://pubs.opengroup.org/onlinepubs/007904975 /basedefs/limits.h.html
也就是说,参数的数量或参数的长度没有单独的限制。仅限制存储所有参数和环境变量所需的总大小。
xargs
使用sysconf(_SC_ARG_MAX );
产生的值与 getconf ARG_MAX 报告的值相同。在 Linux 上,命令行参数和环境变量被放入新进程的堆栈中。因此,进程/线程最大堆栈大小是最终的上限。 Linux 特定的限制硬编码在内核中 :
You can try:
http://pubs.opengroup.org/onlinepubs/007904975/basedefs/limits.h.html
That is, there is no individual limit on the number of arguments or argument's length. Only the limit on total size required to store all the arguments and environment variables.
xargs
figures out maximum command line length usingsysconf(_SC_ARG_MAX);
which yields the same value as reported bygetconf ARG_MAX
.On Linux command line arguments and environment variables are put into new process' stack. So, the process/thread maximum stack size is the ultimate upper bound. Linux-specific limits are hardcoded in the kernel:
这两者都仅受您拥有多少内存(或您的操作系统为您的程序提供了多少内存)的限制。
编辑:实际上,参数的数量也受到
int
大小的限制。Both of those are bounded only by how much memory you have (or how much memory your OS gives your program).
EDIT: Actually, the number of arguments is also bounded by the size of
int
.我认为你误解了这里发生的事情。您无需在代码中向 argv[] 添加任何内容,并且无需担心它们的最大大小。当有人运行你编译的程序时,
你的 main 函数将被调用。
argc
将是 4,argv[0]
将是./javas_program
,argv[1]
将是 < code>argument1、argv[2]
将是argument2
等。在您的程序中,您应该假设
argv[]< 的内容/code> 可以是任意大小。如果您想将它们限制为特定大小,您应该检查它们是否大于该大小。
I think you're misunderstanding what's going on here. You don't, in your code, add anything to argv[], and you don't worry about their maximum sizes. When somebody runs your compiled program, as
then your main function will be called.
argc
will be 4,argv[0]
will be./javas_program
,argv[1]
will beargument1
,argv[2]
will beargument2
, etc.In your program, you should assume that the contents of
argv[]
can be any size. If you want to limit them to a specific size, you should check that they're not larger than that.这可能取决于您用来启动程序的机制。如果它是通过 shell(
bash
或其他),您必须查找它是否施加了限制。如果您通过 execv 或类似的东西启动程序,它们应该只受到与任何数组和字符串相同的限制,并且,正如有人指出的,因为 argc 是 < code>int 由于历史原因,限制为
int
的大小,而不是size_t
。It probably depends on the mechanism you are using to start your program. If it is through a shell (
bash
or whatever) you'd have to look up if it imposes restrictions.If you start your program through
execv
or something similar, they should only be subject to the same restrictions as any array and string, and, as somebody noted, becauseargc
isint
for historical reasons, to the limited size ofint
not ofsize_t
.