11

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DebareDaDauntless
  • 471
  • 2
  • 7
  • 12

2 Answers2

26

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.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • @refp: Adding a comment was fine, but there was no need to complicate the code. – Ben Voigt Oct 18 '13 at 02:31
  • sure the parentheses in conjunction with `sizeof` might have been a stylistic modification to your post, but I sure wouldn't consider it to be a method of making it more complicated. consistancy is key in programming (especially when dealing with novices, easier (for them) to just deal with one "form" of `sizeof` (excuse my weird wording)). – Filip Roséen - refp Oct 18 '13 at 02:36
  • But there are two separate forms of `sizeof` – Ben Voigt Oct 18 '13 at 02:41
  • of course, and our mutual edited comment now make that clear, I guess I don't mind the middle ground. now it's time (04:46am CET) to get some sleep. – Filip Roséen - refp Oct 18 '13 at 02:47
-1
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]);
Pratap
  • 7
  • 3
  • 5
    Please consider adding an explanation. – OhBeWise Mar 17 '16 at 17:14
  • 2
    While this code may answer the question, providing additional context regarding _why_ and/or _how_ this code answers the question would significantly improve its long-term value. Please [edit] your answer to add some explanation. – Toby Speight Mar 17 '16 at 18:25