在C ++中使用memcpy [英] Using memcpy in C++

查看:101
本文介绍了在C ++中使用memcpy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 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];

,我想使用memcopyarr中的元素复制到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);

因为您知道arrnewarr的数据类型,所以指针算术有效.但是在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::copystd::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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆