简体   繁体   English

如何使用 memcpy 将一个数组复制到另一个数组?

[英]How to use memcpy to copy one array to another one?

for (i = 0; i < n1; i++) 
   L[i] = arr[l + i]; 

Because I want to copy a large array,I heard that need to use memcpy.因为要复制一个大数组,听说需要用到memcpy。

memcpy as the name says, copy memory area. memcpy 顾名思义,复制 memory 区域。 is a C standard function under string.h .string.h下的C标准 function 。

void *memcpy(void *dest, const void *src, size_t n); 

description:描述:

The memcpy() function copies n bytes from memory area src to memory area dest . memcpy() function 将n个字节从 memory 区域src复制到 memory 区域dest The memory areas must not overlap . memory 区域must not overlap Use memmove(3) if the memory areas do overlap.如果 memory 区域确实重叠,请使用 memmove(3)。 The memcpy() function returns a pointer to dest. memcpy() function 返回一个pointer to dest 的指针。 for more details goto man7: memcpy有关更多详细信息,请转到 man7: memcpy

so in your case the call would be:所以在你的情况下,电话是:

memcpy(L, &arr[l], n1*sizeof(arr[l]));

sizeof one array elementis:一个数组元素的大小是:

sizeof(arr[l])

make sure that (l+n1) doesnot exceeds the array boundaries.确保(l+n1)不超过数组边界。 its you responsibility.它是你的责任。

memcopy(destination, source, length)

That would be in your case:那将是您的情况:

int len = sizeof(int) * n1;
memcopy(L, arr+l, len);

Note: You may have to fix the length calculation according to the type you are using.注意:您可能必须根据您使用的类型修复长度计算。 Moreover, you should also remember to add 1 to include the \0 character that terminates char arrays if you are dealing with strings.此外,如果您正在处理字符串,您还应该记住添加 1 以包含终止 char arrays 的 \0 字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM