memcpy与memmove详解:
![在这里插入图片描述](https://img-blog.csdnimg.cn/3c31b1d1c3b646febcd5d11703ee4254.png)
将num字节的值从源指向的位置直接复制到目标指向的内存块。
源指针和目标指针所指向的对象的底层类型与此函数无关;结果是数据的二进制副本。
该函数不检查源文件中的任何终止空字符——它总是准确地复制num字节。
为了避免溢出,目标和源参数所指向的数组的大小应该至少为num字节,并且不应该重叠(对于重叠的内存块,memmove是一种更安全的方法
memcpy模拟实现:
#include<stdio.h>
#include<string.h>
#include<assert.h>
void* my_memcpy(void* dest, const void* src, size_t count)
{
void* ret = dest;
assert(dest != NULL);
assert(src != NULL);
while (count--)
{
*(char*)dest = *(char*)src;
++(char*)dest;
++(char*)src;
}
return ret;
}
int main()
{
char arr1[] = "abc";
char arr2[] = "def";
void* ret = my_memcpy(arr1, arr2, 1);
printf("%s", arr1);
return 0;
}
举例:
/* memcpy example */
#include <stdio.h>
#include <string.h>
struct {
char name[40];
int age;
} person, person_copy;
int main ()
{
char myname[] = "Pierre de Fermat";
/* using memcpy to copy string: */
memcpy ( person.name, myname, strlen(myname)+1 );
person.age = 46;
/* using memcpy to copy structure: */
memcpy ( &person_copy, &person, sizeof(person) );
printf ("person_copy: %s, %d \n", person_copy.name, person_copy.age );
return 0;
}
memmove:
将num字节的值从源指向的位置复制到目标指向的内存块。复制发生时,就像使用了中间缓冲区一样,允许目标和源重叠。
源指针和目标指针所指向的对象的底层类型与此函数无关;结果是数据的二进制副本。
该函数不检查源文件中的任何终止空字符——它总是准确地复制num字节。
为了避免溢出,目标参数和源参数所指向的数组的大小应该至少为num字节。
#include<stdio.h>
#include<assert.h>
#include<string.h>
void* my_memmove(void* destination, void* source, size_t num)
{
void* result = destination;
while (num--)
{
if (source > destination)
{
*(char*)destination = *(char*)source;
source = (char*)source + 1;
destination = (char*)destination + 1;
}
else
{
*((char*)destination + num) = *((char*)source + num);
}
}
return result;
}
int main()
{
int a[] = { 1,2,3,4,5,6,7,8,9,10 };
my_memmove(a + 4, a + 2, 20);
for (int i = 0; i < 10; i++)
{
printf("%d ", a[i]);
}
return 0;
}
举例:
/* memmove example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "memmove can be very useful......";
memmove (str+20,str+15,11);
puts (str);
return 0;
}
#include <string.h>
int main ()
{
char str[] = “memmove can be very useful…”;
memmove (str+20,str+15,11);
puts (str);
return 0;
}