在编译对以下函数的调用期间:
char* process_array_of_strings(const char** strings);
当char**
作为参数传递时,GCC 会抱怨:
note: expected ‘const char **’ but argument is of type ‘char **’
虽然该函数不会改变字符(因此是 const),但它确实复制了指针数组以修改字符指针本身,因此常量指针在这里绝对是不可取的。
编译成功,程序似乎正常工作。那么程序员应该如何处理这个警告呢?
使用强制转换显式,编译器会很高兴:
process_array_of_strings((const char**) foo);
在这些情况下,你必须明确地说你知道你在做什么。
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). */
}
从您对process_array_of_strings()
功能的描述来看,它也可能需要const char * const *
,因为它既不修改指针也不修改字符(但在其他地方复制指针)。在这种情况下,上述情况是不可能的,编译器理论上可以允许您在没有警告的情况下自动将char **
转换为const char * const *
,但这不是语言的定义方式。
所以答案显然是你需要一个强制转换(显式)。我写了这个扩展,以便您可以完全理解为什么会出现警告,这在您决定静音时很重要。