【问题标题】:How to copy std::string to char array?如何将 std::string 复制到 char 数组?
【发布时间】:2022-01-05 16:45:23
【问题描述】:

我在将字符串从字符串向量连接到 char 数组时遇到问题。每次我运行代码时,它都会因为 memcpy() 函数中的分段错误错误而自动停止。我希望数据变量包含“Hello World”。

#include <iostream>
#include <vector>
#include <cstring>
using namespace std;

void concatinateString(vector<string> stringVector, char* data) {
    int position = 0;
    //Concatetnate strings from vector to char array
    for (int i = 0; i < (int)stringVector.size(); i++) {
        memcpy((char*)data[position], stringVector[i].c_str(), strlen(stringVector[i].c_str()));
        //Change start byte position
        position += (int)strlen(stringVector[i].c_str());
    }
    //Add null terminator
    data[position] = '\0'; 
}

int main() {
    //Create vector
    vector<string> stringVector;
    stringVector.push_back("Hello");
    stringVector.push_back("World");

    //Allocate memory for char array
    uint32_t dataLength = (uint32_t)(stringVector.size());
    char* data = (char*)calloc(dataLength + 1, sizeof(char)); //+1 for null terminator
    
    concatinateString(stringVector, data);

    //Print result
    cout << "RESULT: " << data << endl;

    //Free memory
    if (data != NULL) free(data);

    //Prevent console automatically close
    cin.get();
    while(1) {}

    return 0;
}

由于我的项目需要,我无法将数据变量的数据类型更改为 std::string。

【问题讨论】:

  • 提示:您希望stringVector.size() 做什么?它给出了结果 2
  • @4386427 我希望它返回stringVector的字节数。
  • 嗯,这种期望是错误的。它不是它在做什么。
  • 抛开学习价值不谈,没有理由手动分配数组。您可以连接成一个std::string,然后将其视为一个数组(使用.data())。
  • @4386427 哇...非常感谢。看起来我对向量中的元素数量和向量大小感到困惑。我的问题解决了。

标签: c++ segmentation-fault memcpy


【解决方案1】:

您实际上可以先连接所有字符串,然后复制到传递的 char 指针中。

代码:

...

void concatinateString(vector<string> stringVector, char* data) {
  string resString;
  // Concatenating all strings into a single string
  for(int i = 0; i < stringVector.size(); i++) {
    resString += stringVector[i];
  }
  // copying the concatenated string into the char buffer
  memcpy(data, resString.c_str(), resString.size());
}

...

【讨论】:

    猜你喜欢
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    • 2011-10-26
    • 1970-01-01
    • 2013-03-20
    • 2012-01-10
    • 2023-03-26
    相关资源
    最近更新 更多