简体   繁体   English

关于char **参数的const char **参数警告

[英]const char** parameter warning about char** argument

During compilation of a call to the following function: 在编译对以下函数的调用期间:

char* process_array_of_strings(const char** strings);

GCC complains when a char** is passed as argument: 当一个char**作为参数传递时,GCC会抱怨:

note: expected ‘const char **’ but argument is of type ‘char **’

While the function does not alter the characters (hence the const) it does duplicate the array of pointers in order to modify the character pointers themselves, so constant pointers are definitely undesirable here. 虽然该函数不会改变字符(因此是const),但它会复制指针数组以便修改字符指针本身,因此这里的常量指针绝对是不可取的。

Compilation succeeds and the program appears to work. 编译成功,程序似乎工作。 So how is the programmer supposed to handle this warning? 那么程序员应该如何处理这个警告呢?

Make the conversion explicit with a cast and the compiler will be happy: 使用强制转换显式转换,编译器会很高兴:

process_array_of_strings((const char**) foo);

In these cases you have to explicitly say that you know what you're doing. 在这些情况下,你必须明确地说你知道你在做什么。

This is why char ** is not automatically converted to const char ** in C++, and why the C compiler issues a warning while allowing it. 这就是为什么char **不会在C ++中自动转换为const char **原因,以及为什么C编译器在允许的情况下发出警告。

/* This function returns a pointer to a string through its output parameter: */
void get_some_string(const char ** p) {
    /* I can do this because p is const char **, so the string won't be modified. */
    *p = "unchangeable string in program core";
}

void f() {
    char * str;
    /* First, I'll call this function to obtain a pointer to a string: */
    get_some_string(&str);
    /* Now, modify the string: */
    for (char * p = str; *p; p++)
        *p = toupper(*p);
    /* We have just overwritten a constant string in program core (or crashed). */
}

From your description of what process_array_of_strings() does, it could just as well take const char * const * because it modifies neither the pointers nor the characters (but duplicates the pointers elsewhere). 根据你对process_array_of_strings()的描述,它也可以采用const char * const *因为它既不修改指针也不修改字符(但在其他地方复制指针)。 In that case, the above scenario would not be possible, and compiler theoretically could allow you to convert char ** to const char * const * automatically without warnings, but that's not how the language is defined. 在这种情况下,上面的场景是不可能的,编译器理论上可以允许你在没有警告的情况下自动将char **转换为const char * const * ,但这不是语言的定义方式。

So the answer is obviously that you need a cast (explicit). 所以答案显然是你需要一个演员(明确的)。 I've written up this expanation so that you can fully understand why the warning appears, which is important when you decide to silence one. 我已经写了这个扩展,以便你可以完全理解警告出现的原因,这对你决定沉默时很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM