问题
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?
回答1:
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.
回答2:
memcpy(dest,src,size)
dest -to which variable
src - from which variable
size - size of src varible
int* arr = new int[5]; //source
int* newarr = new int[6]; // destination
for(int i = 0;i<5;i++) {arr[i] = i * 3;printf(" %d ",arr[i]);}
memcpy(newarr,arr,sizeof(int)* 5);
for(int i = 0;i<5;i++) printf("%d",newarr[i]);
来源:https://stackoverflow.com/questions/19439715/using-memcpy-in-c