C++:无法使用 'char*[x]' 类型的右值初始化 'char**' 类型的变量

C++: cannot initialize a variable of type 'char**' with a rvalue of type 'char*[x]'

本文关键字:类型 char 初始化 变量 C++      更新时间:2023-10-16
char str_arr[] = "ads";
char *str_ptr = str_arr;
char **ptr_str_ptr = &str_ptr;     // OK
char **ptr_str_arr = &str_arr;     // compile error: cannot initialize a variable of type 'char**' with a rvalue of type 'char*[4]'

我很困惑为什么我们不能得到str_arr的地址。什么好主意吗?

可以得到str_arr的地址。然而,它将是一个数组的地址,而不是指针的地址。从本质上讲,赋值失败是因为类型不兼容。

这里有一个例子说明为什么你不能把它分配给指向char的指针,因为这是可能的:

char **ptr_str_arr = &str_arr; // imagine this has worked
*ptr_str_arr = new char[10];   // This cannot be done to an array

由于类型不兼容,这甚至对const指针也不起作用。

char* const* ptr_const_str_arr = &str_arr; // Does not work either

演示。