我在将字符串从字符串向量连接到char数组时遇到问题。每次我运行代码时,都会因为memcpy((函数中的分段错误而自动停止。我希望数据变量包含"0";你好世界";。
#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] = ' ';
}
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。
实际上,您可以首先连接所有字符串,然后复制到传递的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());
}
...