Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memcpy vs for loop - What's the proper way to copy an array from a pointer?

I have a function foo(int[] nums) which I understand is essentially equivalent to foo(int* nums). Inside foo I need to copy the contents of the array pointed to by numsinto some int[10] declared within the scope of foo. I understand the following is invalid:

void foo (int[] nums)  {     myGlobalArray = *nums } 

What is the proper way to copy the array? Should I use memcpy like so:

void foo (int[] nums) {     memcpy(&myGlobalArray, nums, 10); } 

or should I use a for loop?

void foo(int[] nums) {     for(int i =0; i < 10; i++)     {         myGlobalArray[i] = nums[i];     } } 

Is there a third option that I'm missing?

like image 359
mjn12 Avatar asked Jan 18 '11 21:01

mjn12


People also ask

Is memcpy more efficient than for loop?

memcpy is only faster if: BOTH buffers, src AND dst, are 4-byte aligned. if so, memcpy() can copy a 32bit word at a time (inside its own loop over the length)

Does memcpy copy an array?

Memcpy copies data bytes by byte from the source array to the destination array. This copying of data is threadsafe.

What can I use instead of memcpy?

memmove() is similar to memcpy() as it also copies data from a source to destination.

When should memcpy be used?

The function memcpy() is used to copy a memory block from one location to another. One is source and another is destination pointed by the pointer. This is declared in “string.


2 Answers

Yes, the third option is to use a C++ construct:

std::copy(&nums[0], &nums[10], myGlobalArray); 

With any sane compiler, it:

  • should be optimum in the majority of cases (will compile to memcpy() where possible),
  • is type-safe,
  • gracefully copes when you decide to change the data-type to a non-primitive (i.e. it calls copy constructors, etc.),
  • gracefully copes when you decide to change to a container class.
like image 107
Oliver Charlesworth Avatar answered Oct 14 '22 07:10

Oliver Charlesworth


Memcpy will probably be faster, but it's more likely you will make a mistake using it. It may depend on how smart your optimizing compiler is.

Your code is incorrect though. It should be:

memcpy(myGlobalArray, nums, 10 * sizeof(int) ); 
like image 40
Jay Avatar answered Oct 14 '22 06:10

Jay