【问题标题】:How can I convert list<string> to char**? [duplicate]如何将 list<string> 转换为 char**? [复制]
【发布时间】:2012-03-12 06:35:47
【问题描述】:

可能重复:
Converting a std::list to char*[size]

如何将字符串列表、列表转换为 char** ? 有什么方法可以使用可用的 STL 成员方法。如果没有,我该如何实现?

我正在调用一个 C 函数,该函数将输入作为 char**,来自 C++,其中包含要发送的字符串列表。

【问题讨论】:

    标签: c++ string list pointers stl


    【解决方案1】:

    不幸的是,列表中的元素在内存中不是连续的,因此没有直接的方法可以将列表转换为数组。所以你的方法应该做的是分配一个新数组,然后复制字符串。如果您只想要一个 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-&gt;size()+1]; memcpy(array[index],it-&gt;c_str(), it-&gt;size()+1);。改用strdup() 可能会更好。
    • 感谢您的 cmets,我想我相信我已经修复了我的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 2011-05-11
    • 1970-01-01
    • 2019-12-03
    • 2013-08-26
    • 2020-01-11
    • 2019-07-28
    相关资源
    最近更新 更多