像这样:
// allocate memory for n char pointers dynamically.
char ** lit = static_cast<char**>(::operator new(n * sizeof(char*)));
for (unsigned int i = 0; i != n; ++i)
{
lit[i] = static_cast<char*>(::operator new(length_of_string_i)); // #1
// populate lit[i] with data
}
您需要一些方法来确定i
第 th 字符串的长度,您需要将其适当地粘贴到标记为 #1 的行中。请注意sizeof(char) == 1
,因此您不需要在内部分配中乘以任何东西。(如果你愿意,你可以使用std::malloc
,::operator new
但你必须这样做#include <cstdlib>
。)完成后不要忘记清理!
这当然只是你所要求的字面翻译。在 C++ 中,您通常更喜欢创建对象而不是原始内存分配,如下所示:
// construct n char pointers dynamically
char ** lit = new char*[n];
for (unsigned int i = 0; i != n; ++i)
{
lit[i] = new char[length_of_string_i];
// populate lit[i] with data
}
但是你不应该认真地使用array-new。这不是一个好的概念,也很少是好的 C++。
因此,您根本不应该这样做,而应该使用:
std::vector<std::string> lit(n);