在C ++中使用memcpy [英] Using memcpy in C++
问题描述
对于 memcpy 函数的参数,我有点困惑.如果我有
I am little confused on the parameters for the memcpy function. If I have
int* arr = new int[5];
int* newarr = new int[6];
,我想使用memcopy
将arr
中的元素复制到newarr
中,
and I want to copy the elements in arr
into newarr
using memcopy
,
memcpy(parameter, parameter, parameter)
我该怎么做?
推荐答案
因此顺序为memcpy(destination, source, number_of_bytes)
.
因此,您可以使用
memcpy(newarr, arr, 5 * sizeof *arr);
/* sizeof *arr == sizeof arr[0] == sizeof (int) */
或以
memcpy(newarr+1, arr, 5 * sizeof *arr);
因为您知道arr
和newarr
的数据类型,所以指针算术有效.但是在memcpy
内部,它不知道类型,因此它需要知道字节数.
Because you know the data type of arr
and newarr
, pointer arithmetic works. But inside memcpy
it doesn't know the type, so it needs to know the number of bytes.
另一种选择是std::copy
或std::copy_n
.
std::copy_n(arr, 5, newarr);
对于像int
这样的基本类型,由memcpy
完成的按位复制将可以正常工作.对于实际的类实例,您需要使用std::copy
(或copy_n
),以便使用该类的自定义赋值运算符.
For fundamental types like int
, the bitwise copy done by memcpy
will work fine. For actual class instances, you need to use std::copy
(or copy_n
) so that the class's customized assignment operator will be used.
这篇关于在C ++中使用memcpy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!