如何将 main 的 *argv[] 传递给函数?
我有一个可以接受命令行参数的程序,并且我想从函数访问用户输入的参数。如何将 *argv[]
从 int main( int argc, char *argv[])
传递到该函数?我对指针的概念有点陌生,并且 *argv[]
看起来有点太复杂了,我无法自己解决这个问题。
这个想法是通过将我想要使用参数完成的所有工作移动到库文件中,使我的 main
尽可能干净。当我设法在 main
之外获取这些参数时,我已经知道如何处理它们。我只是不知道如何让他们到达那里。
我正在使用海湾合作委员会。 提前致谢。
I have a program that can accept command-line arguments and I want to access the arguments, entered by the user, from a function. How can I pass the *argv[]
, from int main( int argc, char *argv[])
to that function ? I'm kind of new to the concept of pointers and *argv[]
looks a bit too complex for me to work this out on my own.
The idea is to leave my main
as clean as possible by moving all the work, that I want to do with the arguments, to a library file. I already know what I have to do with those arguments when I manage to get hold of them outside the main
. I just don't know how to get them there.
I am using GCC.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需编写一个函数,然后
在
main
中将其调用为parse_cmdline(argc, argv)
即可。不涉及魔法。事实上,您实际上并不需要传递 argc,因为 argv 的最终成员保证是空指针。但既然你有 argc,你不妨传递它。
如果函数不需要知道程序名称,您也可以决定将其调用为
Just write a function such as
and call that in
main
asparse_cmdline(argc, argv)
. No magic involved.In fact, you don't really need to pass
argc
, since the final member ofargv
is guaranteed to be a null pointer. But since you haveargc
, you might as well pass it.If the function need not know about the program name, you can also decide to call it as
或者……
然后……
Or...
And then...
只需将 argc 和 argv 传递给您的函数即可。
Just pass
argc
andargv
to your function.