I have an std::vector. I want to copy the contents of the vector into a char* buffer of a certain size.
Is there a safe way to do this?
Can I do this?
memcpy(buffer, _v.begin(), buffer_size);
or this?
std::copy(_v.begin(), _v.end(), buffer); // throws a warning (unsafe)
or this?
for (int i = 0; i < _v.size(); i++)
{
*buffer = _v[i];
buffer++;
}
Thanks..
Using strcpy function The idea is to use the c_str() function to convert the std::string to a C-string. Then we can simply call the strcpy() function to copy the C-string into a char array.
The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0'). It returns a null pointer to the string.
char test [] = { 'a', 'b', 'c', 'd', 'e' }; vector<char[]> v; v. push_back(test);
std::copy(_v.begin(), _v.end(), buffer);
This is preferred way to do this in C++. It is safe to copy this way if buffer
is large enough.
If you just need char*
, then you can do this:
char *buffer=&v[0];//v is guaranteed to be a contiguous block of memory.
//use buffer
Note changing data pointed to by buffer
changes the vector's content also!
Or if you need a copy, then allocate a memory of size equal to v.size()
bytes, and use std::copy
:
char *buffer = new char[v.size()];
std::copy(v.begin(), v.end(), buffer);
Dont forget to delete []buffer;
after you're done, else you'll leak memory.
But then why would you invite such a problem which requires you to manage the memory yourself.. especially when you can do better, such as:
auto copy = v; // that's simpler way to make copies!!
// and then use copy as new buffer.
// no need to manually delete anything. :-)
Hope that helps.
The safest way to copy a vector<char>
into a char *
buffer is to copy it to another vector, and then use that vector's internal buffer:
std::vector<char> copy = _v;
char * buffer = ©[0];
Of course, you can also access _v
s buffer if you don't actually need to copy the data. Also, beware that the pointer will be invalidated if the vector is resized.
If you need to copy it into a particular buffer, then you'll need to know that the buffer is large enough before copying; there are no bounds checks on arrays. Once you've checked the size, your second method is best. (The first only works if vector::iterator
is a pointer, which isn't guaranteed; although you could change the second argument to &_v[0]
to make it work. The third does the same thing, but is more complicated, and probably should be fixed so it doesn't modify buffer
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With