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
Demo.