0

I am developing in Cocoa / Xcode and have an int * array containing values. When I want to use memcpy to shift values in the array, it transfers only 0s.

e.g.

  • Array contains values as 1 2 3 4
  • memcpy(array,array+2*sizeof(int),2*sizeof(int));

result: 0,0,3,4

Is there a better alternative to memcpy, or something I am doing wrong ?

2 Answers 2

7

I think the right way to do what you want is:

memcpy(array, array + 2, 2*sizeof(int));

That's because in the 2nd argument of memcpy pointer arithmetic is being done, and anything that's being added to "array" pointer is considered as being a multiple of an integer's size. So in this case saying "array + 2" means "the integer pointer `array' plus two times the size of an integer".

1
  • 2
    Personally I would prefer "memcpy(array, array+2, 2*sizeof array[0] );". Will work independent from the type of array, even in a macro. Commented Sep 25, 2011 at 17:28
0

The manpage to memcpy says, that the regions should not overlap. Try memmove instead.

2
  • Thanks, but the regions do not overlap here because I am just copying the 3 and 4 to the 1 and 2. Tried with memmove however and result is unfortunately the same... Commented Sep 25, 2011 at 17:00
  • Why in the world would you use memcpy for 2 ints rather than just writing array[0]=array[2]; array[1]=array[3];?? Commented Sep 26, 2011 at 0:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.