我对 C++ 很陌生。我正在尝试调用一个接受 char** 的函数:
bool func(char** a) {
//blablabla
}
所以它需要一个 c 字符串数组。我需要创建一个 char**,但没有任何效果。
char** a = char[255][255]; // error: type name is not allowed
char** a = new char[255][255]; // error: a value of type "char (*)[255]" cannot be used to initialize an entity of type "char **"
char a[][] = {"banana", "apple"};
char** b = &a; // error: a value of type "<error-type> (*)[2]" cannot be used to initialize an entity of type "char **"
最后我需要做:
char* a[] = {"banana", "apple"};
为什么前几个不起作用,为什么最后一个起作用?
提前致谢。
原文由 Boyang 发布,翻译遵循 CC BY-SA 4.0 许可协议
你的代码有很多错误。
首先,这甚至不是有效的 C++(或 C)。也许你的意思是:
无论如何,请始终记住,二维动态分配数组的类型不是
**
而是(*)[N]
这是非常不同的。您在评论中提供的错误消息准确地解释了我之前所说的。
在上面的代码中,变量
a
的正确类型应该是char* a[]
。同样,数组和指针(就类型而言)是非常不同的东西。char
数组可能会衰减为指针(如果NULL
终止),但对于其余部分,除了显式强制转换外,您不能像现在这样使用指针和数组。最后一个有效,因为就像我之前所说的那样,
char* []
是 C 字符串数组的正确类型。无论如何,如果你只是做功课,学习这些东西是可以的。但是在使用 C++ 的未来开发中:尽量不要使用以
C-
开头的“特性”,如 C 字符串、C 数组等。C++ 的标准库为您提供std::string
,std::array
,std::vector
等 _免费_。If you really need to allocate dynamic memory (with
new
anddelete
, ornew[]
anddelete[]
) please use smart pointers , likestd::shared_ptr
或std::unique_ptr
。