Copy the contents of std::vector<char> into a char* buffer?

22,723

Solution 1

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.

Solution 2

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.

Solution 3

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 = &copy[0];

Of course, you can also access _vs 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).

Share:
22,723
krebstar
Author by

krebstar

Updated on September 09, 2020

Comments

  • krebstar
    krebstar over 3 years

    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..