Search code examples
c++vectorcopystdmemcpy

Can I use std::copy to copy bit pattern of data from vector of integers to an array of unsigned char


Recently I have been trying to update some code to utilise the standard C++ library functions rather than old C style functions. In particular, I tried to do the following (artificial working example for simplicity - i know the code is ugly but it illustrates the problem concisely) :

std::vector<int> vData;
vData.push_back(10990);
vData.push_back(11990);
vData.push_back(12990);
vData.push_back(13990);

unsigned char szBuffer[100];
memset(szBuffer,0,sizeof(szBuffer));

std::copy(vData.begin(),vData.end(),szBuffer);

I was expecting that this would behave in a similar way to the code that I am trying to replace :

memcpy(szBuffer,&vData[0],sizeof(int)*vData.size());

but debugging the code, it is clear that the std::copy code I have written is only writing to the first 4 bytes of the unsigned char buffer instead of the full bit pattern of the 4 integers in the vector. Can someone tell me what I have done wrong, or is it simply that I cannot use std::copy in this way and should stick with memcpy ?


Solution

  • Stick to memcpy, std::copy is being intelligent, it understands the types involved and is correctly converting int to unsigned char using standard conversions. memcpy is ignorant, that's what you want.