Jump to content
  • Advertisement
Sign in to follow this  
chris_01

Replace char* with std::vector

This topic is 2145 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

 

 

Share this post


Link to post
Share on other sites
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?

Edited by Juliean

Share this post


Link to post
Share on other sites

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
 
 
Edited by chris_01

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites


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?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!