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

Spread the love

Question Description

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?

Practice As Follows

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) );

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.