C语言 如何将 main 的 *argv[] 传递给函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7882810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I pass main's *argv[] to a function?
提问by Eternal_Light
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.
我有一个可以接受命令行参数的程序,我想从函数中访问用户输入的参数。如何将*argv[], from传递int main( int argc, char *argv[])给该函数?我对指针的概念*argv[]有点陌生,看起来有点太复杂了,我无法自己解决。
The idea is to leave my mainas 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.
这个想法是main通过将我想要处理参数的所有工作移到一个库文件中来尽可能地保持干净。当我设法在main. 我只是不知道如何让他们到达那里。
I am using GCC. Thanks in advance.
我正在使用 GCC。提前致谢。
回答by Fred Foo
Just write a function such as
只需编写一个函数,例如
void parse_cmdline(int argc, char *argv[])
{
// whatever you want
}
and call that in mainas parse_cmdline(argc, argv). No magic involved.
并将其main称为 as parse_cmdline(argc, argv)。不涉及魔法。
In fact, you don't really need to pass argc, since the final member of argvis guaranteed to be a null pointer. But since you have argc, you might as well pass it.
实际上,您实际上并不需要传递argc,因为argv保证的最终成员是空指针。但既然你有argc,你不妨通过它。
If the function need not know about the program name, you can also decide to call it as
如果函数不需要知道程序名称,您也可以决定将其调用为
parse_cmdline(argc - 1, argv + 1);
回答by Basile Starynkevitch
Just pass argcand argvto your function.
只需传递argc和argv到您的功能。
回答by Ed S.
SomeResultType ParseArgs( size_t count, char** args ) {
// parse 'em
}
Or...
或者...
SomeResultType ParseArgs( size_t count, char* args[] ) {
// parse 'em
}
And then...
进而...
int main( int size_t argc, char* argv[] ) {
ParseArgs( argv );
}

