在 C++ 中初始化 char**
Initialising char** in c++
我看了大部分相关帖子,但不幸的是,我的具体案例没有得到满意的答案。
我正在使用第 3 方库,该库的结构的属性为 char**
,我需要填充它。我尝试了几乎所有我认为有效的 c++ 语法并且可以工作的可以想象的东西,但是我总是在尝试分配它时遇到 运行 时间错误。
为了澄清,我应该说字符串数组应该采用(我假设)文件名。
将此视为我们的代码:
char** listOfNames; // belongs to the 3rd party lib - cannot change it
listOfNames = // ???
所以我的问题是如何用一个或多个字符串文件名初始化这个变量,例如:"myfile.txt" ?
也应该是c++11兼容的。
类似
char** listOfNames; // belongs to the 3rd party lib - cannot change it
try
{
listOfNames = new char*[10] { "Hello", "world", ... };
}
catch (std::exception const& e)
{
// delete the arrays here...
// ...
std::cout << e.what();
}
?
我认为你应该将 listOfNames
初始化为动态字符串数组,然后按以下代码初始化数组的每个元素:
char** listOfNames; // belongs to the 3rd party lib - cannot change it
int iNames = 2; // Number of names you need
try
{
// Create listOfNames as dynamic string array
listOfNames = new char*[iNames];
// Then initialize each element of the array
// Element index must be less than iNames
listOfNames[0] = "Hello";
listOfNames[1] = "World";
}
catch (std::exception const& e)
{
std::cout << e.what();
}
我看了大部分相关帖子,但不幸的是,我的具体案例没有得到满意的答案。
我正在使用第 3 方库,该库的结构的属性为 char**
,我需要填充它。我尝试了几乎所有我认为有效的 c++ 语法并且可以工作的可以想象的东西,但是我总是在尝试分配它时遇到 运行 时间错误。
为了澄清,我应该说字符串数组应该采用(我假设)文件名。
将此视为我们的代码:
char** listOfNames; // belongs to the 3rd party lib - cannot change it
listOfNames = // ???
所以我的问题是如何用一个或多个字符串文件名初始化这个变量,例如:"myfile.txt" ?
也应该是c++11兼容的。
类似
char** listOfNames; // belongs to the 3rd party lib - cannot change it
try
{
listOfNames = new char*[10] { "Hello", "world", ... };
}
catch (std::exception const& e)
{
// delete the arrays here...
// ...
std::cout << e.what();
}
?
我认为你应该将 listOfNames
初始化为动态字符串数组,然后按以下代码初始化数组的每个元素:
char** listOfNames; // belongs to the 3rd party lib - cannot change it
int iNames = 2; // Number of names you need
try
{
// Create listOfNames as dynamic string array
listOfNames = new char*[iNames];
// Then initialize each element of the array
// Element index must be less than iNames
listOfNames[0] = "Hello";
listOfNames[1] = "World";
}
catch (std::exception const& e)
{
std::cout << e.what();
}