简体   繁体   中英

how to copy char* to a vector<char> and retrieve it?

I have char *RecBuffer , int *packetLength point to the data and the size

int i=0;
vector<char> temp;//copy the buffer
while(i<*packetLength)
{
temp.push_back(*(RecBuffer+i));
i++;
}

    ...do something 

//retrieve it now
RecBuffer = temp ????

I believe the easiest way to populate the vector is using the constructor:

vector<char> temp(RecBuffer, RecBuffer + *packetLength);

As for retrieving it back, use the method data :

RecBuffer = temp.data();

NOTE: data will only be available in C++11 in case you do not compile using the new standard, use &temp[0] as proposed by @juanchopanza.

You could say

RecBuffer = temp.data();

or

RecBuffer = &temp[0];

if you don't have c++11 support.

but you have to beware that the data will get deleted when the vector goes out of scope. You will also get a dangling pointer if the vector gets resized.

You can use the constructor of std::vector to copy data from the RecBuffer :

std::vector<char> temp(RecBuffer, RecBuffer + *PacketLength);

You can then use std::vector::data to get access to the underlying array:

RecBuffer = temp.data();

Of course, the underlying array does not exist any more once temp is destroyed.

Try looking up the methods of std::vector to see if there is something useful.

There are some algorithms in <algorithm> that are useful.
std::copy(temp.begin(), temp.end(), RecBuffer);

You could do it the long way:

const unsigned int length = temp.size();
for (unsigned int i = 0; i < packetLength)
{
    RecBuffer[i] = temp[i];
}

I feel it would be safer to perform the following

free(RecBuffer);
RecBuffer = (char *) malloc(sizeof(char) * packetLength);
memcpy(RecBuffer, temp.data(), packetLength);

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