Using memcpy in C++

IkeJoka picture IkeJoka · Oct 18, 2013 · Viewed 59.3k times · Source

I am little confused on the parameters for the memcpy function. If I have

int* arr = new int[5];

int* newarr = new int[6];

and I want to copy the elements in arr into newarr using memcopy,

memcpy(parameter, parameter, parameter)

How do I do this?

Answer

Ben Voigt picture Ben Voigt · Oct 18, 2013

So the order is memcpy(destination, source, number_of_bytes).

Therefore, you can place the old data at the beginning of newarr with

memcpy(newarr, arr, 5 * sizeof *arr);
/* sizeof *arr == sizeof arr[0]  == sizeof (int) */

or at the end with

memcpy(newarr+1, arr, 5 * sizeof *arr);

Because you know the data type of arr and newarr, pointer arithmetic works. But inside memcpy it doesn't know the type, so it needs to know the number of bytes.

Another alternative is std::copy or std::copy_n.

std::copy_n(arr, 5, newarr);

For fundamental types like int, the bitwise copy done by memcpy will work fine. For actual class instances, you need to use std::copy (or copy_n) so that the class's customized assignment operator will be used.