【发布时间】:2012-03-12 06:35:47
【问题描述】:
如何将字符串列表、列表转换为 char** ? 有什么方法可以使用可用的 STL 成员方法。如果没有,我该如何实现?
我正在调用一个 C 函数,该函数将输入作为 char**,来自 C++,其中包含要发送的字符串列表。
【问题讨论】:
标签: c++ string list pointers stl
如何将字符串列表、列表转换为 char** ? 有什么方法可以使用可用的 STL 成员方法。如果没有,我该如何实现?
我正在调用一个 C 函数,该函数将输入作为 char**,来自 C++,其中包含要发送的字符串列表。
【问题讨论】:
标签: c++ string list pointers stl
不幸的是,列表中的元素在内存中不是连续的,因此没有直接的方法可以将列表转换为数组。所以你的方法应该做的是分配一个新数组,然后复制字符串。如果您只想要一个 const char 数组并且在使用 const char 数组时列表不会改变,那么您可以执行以下操作:
void UseListOfString(const std::list<std::string>& l) {
const char** array = new const char*[l.size()];
unsigned index = 0;
for (std::list<std::string>::const_iterator it = l.begin(); it != l.end(); ++it) {
array[index]= it->c_str();
index++;
}
// use the array
delete [] array;
}
如果列表可以更改或者您需要不同于 const 数组的内容,则需要复制字符串:
void UseListOfString(const std::list<std::string>& l) {
unsigned list_size = l.size();
char** array = new char*[list_size];
unsigned index = 0;
for (std::list<std::string>::const_iterator it = l.begin(); it != l.end(); ++it) {
array[index] = new char[it->size() + 1];
memcpy(array[index], it->c_str(), it->size());
array[it->size()] = 0;
}
// use the array
for (unsigned index = 0; index < list_size; ++index) {
delete [] array[index];
}
delete [] array;
}
希望这个答案有帮助。
【讨论】:
for 循环的内容分配了错误的类型,并且字符串不是以空值结尾的(请避免使用strncpy())。试试array[index] = new char[it->size()+1]; memcpy(array[index],it->c_str(), it->size()+1);。改用strdup() 可能会更好。