简体   繁体   中英

How to copy std::string to char array?

I am having trouble concatenating strings from a vector of strings to a char array. Everytime I run the code, it stop automatically because of a segmentation fault error in memcpy() function. I want the data variable to contain "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;
}

I can't change data type of data variable to std::string due to the requirement of my project.

You can actually first concat all strings and copy then into the passed char pointer.

Code:

...

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());
}

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM