Replace char* with std::vector

Started by
5 comments, last by chris_01 10 years, 7 months ago

I try to replace a char* to strore data values with a std::vector<uint8_t> m_vec but I fail.

To write my data I try:


void addData(unsigned int length, unsigned int size, void* data){
    const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data);
    std::copy(ptr,ptr+size, std::back_inserter(m_vec));
}

To test this I try:


unsigned int test1 = 167;
this->addData(1, sizeof(unsigned int), &test1);

unsigned int value = 0;
memcpy(&value, &m_vec, sizeof(unsigned int));
std::cout << "Return: " << value << std::endl;

But I got an invalid value 4920432.

Any idea what I've made wrong?

Advertisement

Any idea what I've made wrong?

Try


memcpy(&value, &m_vec[0], sizeof(unsigned int));

To copy the value out of the vector instead, you were trying to copy the ptr to the vector. Or, even better, step through the debugger. Does the vector at least contain the right value?

Thanks for the hint with the missing vector position. But this solves not the issue. Now memcopy returns an invalid value with 1819213991.

But the buffer contains the correct value of 167. When I cast the value to unsigned int and return it, the correct value is streamed out,

but not when I use memcopy following your instructions ...


 unsigned int v = m_vec[0];
 std::cout << "Vec value: " << v << std::endl;              // returns correct value of 167

 unsigned int v2 = 0;
 memcpy(&v2, &blop.vec[0], sizeof(unsigned int));
  std::cout << "Vec value 2 " << v2 << std::endl;  // returns invalid value

You are memcpy'ing 4 elements of the vector because you use sizeof(unsigned int). What gets printed depends on what the values in m_vec[0] to m_vecc[3] are when interpreted as an unsigned int.

You probably want to memcpy with sizeof(uint8_t).

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley


You probably want to memcpy with sizeof(uint8_t).

Doesn't memcpy require both source and destination being the same size? Unless you specially want to do things different, but since value is 4 bytes, and the vectore store 1 byte, shouldn't that be incompatible anyways?

Nope, memcpy takes void*'s so anything goes (even bugs).

std::copy is what you should use to copy from one compatible iterator to another.

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

Thanks for your advises. Now it works with memcopy also with std::copy.

This topic is closed to new replies.

Advertisement