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 nums
into 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?
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)
Memcpy copies data bytes by byte from the source array to the destination array. This copying of data is threadsafe.
memmove() is similar to memcpy() as it also copies data from a source to destination.
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.
Yes, the third option is to use a C++ construct:
std::copy(&nums[0], &nums[10], myGlobalArray);
With any sane compiler, it:
memcpy()
where possible),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) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With