main() 的参数是什么? [英] What are the arguments to main() for?
问题描述
每次我用 Xcode 创建一个项目(标准命令行实用程序)时,我的main 函数看起来像这样:
Everytime I create a project (standard command line utility) with Xcode, my main function starts out looking like this:
int main(int argc, const char * argv[])
括号里是什么?为什么要使用这个而不仅仅是int main()
?
What's all this in the parenthesis? Why use this rather than just
int main()
?
推荐答案
main 接收参数的数量以及启动程序时传递给它的参数,以便您可以访问它.
main receives the number of arguments and the arguments passed to it when you start the program, so you can access it.
argc 包含参数的数量,argv 包含指向参数的指针.argv[argc] 总是一个 NULL 指针.参数通常包括程序名称本身.
argc contains the number of arguments, argv contains pointers to the arguments. argv[argc] is always a NULL pointer. The arguments usually include the program name itself.
通常,如果你像 ./myprogram
- argc 为 1;
- argv[0] 是字符串./myprogram"
- argv[1] 是一个空指针
如果你像 ./myprogram/tmp/somefile
- argc 为 2;
- argv[0] 是字符串./myprogram"
- argv[1] 是字符串 "/tmp/somefile"
- argv[2] 是一个空指针
这篇关于main() 的参数是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!