如何在C ++中声明一个指向常量的指针? [英] How to declare a pointer to pointer to constant in C++?
问题描述
我正在尝试编写一个函数来解析命令行参数.这是函数声明:
I'm trying to write a function to parse command line arguments. This is the function declaration:
void parse(int, char const **);
以防万一,我还使用typedef const char cchar
尝试了(const char)**
,const char **
和cchar **
.但是,如果我将char **
传递给函数,所有这些(如所期望的,因为它们应该都相同)会导致错误,如:
Just in case, I have also tried (const char)**
, const char **
, and cchar **
using a typedef const char cchar
. However, all of these (as expected, since they should all be identical) result in an error if I pass a char **
into the function, as in:
void main(int argc, char **argv) {
parse(argc, argv);
我从GNU编译器中得到的错误是error: invalid conversion from 'char**' to 'const char**'
,而从Clang中得到的错误是candidate function not viable: no known conversion from 'char **' to 'const char **' for 2nd argument
.
The error I get from GNU's compiler is error: invalid conversion from 'char**' to 'const char**'
and the one from Clang is candidate function not viable: no known conversion from 'char **' to 'const char **' for 2nd argument
.
我已经看到这样的解决方案,建议将其声明为指向char的const指针(const char * const *
),但是我不希望任何一个指针都为const,因为我希望能够修改该指针,以便进行迭代在使用for(; **argv; ++*argv)
的参数上.我该如何声明指向const char的非const指针的非const指针"?
I have seen such solutions suggested as declaring a pointer to a const pointer to char (const char * const *
), but I don't want either pointer to be const because I want to be able to modify the pointer so I can iterate over an argument using for(; **argv; ++*argv)
. How can I declare a "non-const pointer to non-const pointer to const char"?
推荐答案
最安全的签名可以防止修改参数,同时允许任何其他const
组合调用该函数:
The safest signature that prevents modification of the arguments whilst allowing any other const
combination to call the function is this:
parse(int argc, char const* const* argv);
这意味着argv
是const
的指针 是const char
您可以愉快地遍历这样的参数:
You can happily iterate over the parameters like this:
for(auto arg = argv + 1; *arg; ++arg)
{
if(!std::strcmp(*arg, "--help"))
return print_help();
else if(!std::strcmp(*arg, "-v") || !std::strcmp(*arg, "--verbose"))
verbose_flag = true;
// ... etc...
}
请注意,由于字符数组的数组以 null终止,因此不需要接受变量int argc
.
Notice there is no need to accept the variable int argc
because the array of character arrays is null terminated.
所以我通常使用这个:
struct config
{
// program options and switches
};
config parse_commandline(char const* const* argv);
这篇关于如何在C ++中声明一个指向常量的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!