C++ copy std::string to char array with no null termination C++ copy std::string to char array with no null termination arrays arrays

C++ copy std::string to char array with no null termination


You can't use strcpy because that looks for the NULL terminator to identify the end of the string, and copies the NULL to the output string.

Since you're going from a string to a char buffer, the simplest thing would be to use std::copy:

#include <algorithm>static const size_t data_size = 32;struct block{    char data[data_size];};/* ... */std::string buffer = stringArray1[0] + stringArray2[0];std::copy( buffer.begin(), buffer.end(), blocks[0].data );

And, by the way, you might be able to use a vector<char>, rather than a char data[32]

EDIT:

An aside: VC6 is an ancient compiler which was bad when it came out, terrible when the C++ Standard was ratified, and is completely unsupported by Microsoft. If something were to go wrong with it, they won't even talk to you. You should get off VC6 as soon as possible.


Use memcpy instead of strcpy, that's what it's there for:

memcpy(blocks[0].data, buffer.data(), sizeof(blocks[0].data)); 


Use strncpy() instead of strcpy():

strncpy(blocks[0].data, buffer.c_str(), 32);