如何从 main() 函数外部访问 argv[]?
我碰巧有几个函数可以通过 argv[] 数组访问程序的不同参数。目前,这些函数嵌套在 main()
函数中,因为编译器提供了允许此类结构的语言扩展。
我想摆脱嵌套函数,以便在不依赖语言扩展的情况下实现互操作性。
首先,我想到了一个数组指针,一旦程序启动,我将指向 argv[] ,该变量将位于 main()
函数之外并在之前声明功能,以便他们可以使用它。
所以我声明了这样一个指针,如下所示:
char *(*name)[];
它应该是一个指向字符指针数组的指针。但是,当我尝试将其指向 argv[] 时,我收到关于不兼容指针类型的赋值的警告:
name = &argv;
可能是什么问题?您是否想到了另一种从 main()
函数外部访问 argv[] 数组的方法?
I happen to have several functions which access different arguments of the program through the argv[]
array. Right now, those functions are nested inside the main()
function because of a language extension the compiler provides to allow such structures.
I would like to get rid of the nested functions so that interoperability is possible without depending on a language extension.
First of all I thought of an array pointer which I would point to argv[]
once the program starts, this variable would be outside of the main()
function and declared before the functions so that it could be used by them.
So I declared such a pointer as follows:
char *(*name)[];
Which should be a pointer to an array of pointers to characters. However, when I try to point it to argv[]
I get a warning on an assignment from an incompatible pointer type:
name = &argv;
What could be the problem? Do you think of another way to access the argv[]
array from outside the main()
function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就可以了:)
你会看到
char *(*name) []
是一个指向 char 指针数组的指针。而函数参数 argv 的类型为指向 char 的指针,因此 &argv 的类型为指向 char 的指针。为什么?因为当您声明一个函数接受数组时,对于编译器来说,它与接受指针的函数相同。也就是说,是完全相同的等效声明。并不是说数组是指针,而是作为函数参数它是
HTH
will do the trick :)
you see
char *(*name) []
is a pointer to array of pointers to char. Whereas your function argument argv has type pointer to pointer to char, and therefore &argv has type pointer to pointer to pointer to char. Why? Because when you declare a function to take an array it is the same for the compiler as a function taking a pointer. That is,are absolutely identical equivalent declarations. Not that an array is a pointer, but as a function argument it is
HTH
这应该有效,
This should work,