Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stl

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

1 Answers

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.

like image 171
Ivaylo Strandjev Avatar answered Dec 07 '25 01:12

Ivaylo Strandjev