在 C++ 中使用 memcpy
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19439715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using memcpy in C++
提问by IkeJoka
I am little confused on the parameters for the memcpyfunction. If I have
我对memcpy函数的参数有点困惑。如果我有
int* arr = new int[5];
int* newarr = new int[6];
and I want to copy the elements in arrinto newarrusing memcopy,
我想将元素复制arr到newarrusing 中memcopy,
memcpy(parameter, parameter, parameter)
How do I do this?
我该怎么做呢?
回答by Ben Voigt
So the order is memcpy(destination, source, number_of_bytes).
所以顺序是memcpy(destination, source, number_of_bytes)。
Therefore, you can place the old data at the beginning of newarrwith
因此,您可以将旧数据放在newarrwith的开头
memcpy(newarr, arr, 5 * sizeof *arr);
/* sizeof *arr == sizeof arr[0] == sizeof (int) */
or at the end with
或最后
memcpy(newarr+1, arr, 5 * sizeof *arr);
Because you know the data type of arrand newarr, pointer arithmetic works. But inside memcpyit doesn't know the type, so it needs to know the number of bytes.
因为您知道arrand的数据类型newarr,所以指针算术有效。但是memcpy它内部不知道类型,所以它需要知道字节数。
Another alternative is std::copyor std::copy_n.
另一种选择是std::copy或std::copy_n。
std::copy_n(arr, 5, newarr);
For fundamental types like int, the bitwise copy done by memcpywill 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.
对于像 一样的基本类型int,按位复制完成的memcpy工作会很好。对于实际的类实例,您需要使用std::copy(或copy_n) 以便使用类的自定义赋值运算符。
回答by Pratap
memcpy(dest,src,size)
dest -to which variable
src - from which variable
size - size of src varible
int* arr = new int[5]; //source
int* newarr = new int[6]; // destination
for(int i = 0;i<5;i++) {arr[i] = i * 3;printf(" %d ",arr[i]);}
memcpy(newarr,arr,sizeof(int)* 5);
for(int i = 0;i<5;i++) printf("%d",newarr[i]);

