memcpy的VS for循环 - 什么是从一个指针复制一个数组的正确方法? [英] memcpy vs for loop - What's the proper way to copy an array from a pointer?
问题描述
我有一个函数美孚(INT [] NUMS)
我的理解基本上等同于美孚(INT * NUMS)
。在富
我需要通过 NUMS到数组指向的内容拷贝
进入一些 INT [10]
富
的范围内声明。据我所知,以下是无效的:
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
}
什么是数组复制的正确方法?我应该使用的memcpy像这样:
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可能会更快,但它更可能你会用它犯了一个错误。
这可能取决于你的优化编译器是多么的聪明的。
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.
您code不正确,但。它应该是:
Your code is incorrect though. It should be:
memcpy(&myGlobalArray, nums, 10 * sizeof(int) );
这篇关于memcpy的VS for循环 - 什么是从一个指针复制一个数组的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!