1memcpy函数的参数和返回值
1.1参数
目的地(destination)
指向要在其中复制内容的目标数组的指针,类型转换为 void* 类型的指针。
源(source)
指向要复制的数据源的指针,类型转换为 const void* 类型的指针。
数字(num)
要复制的字节数。size_t 是无符号整数类型。
1.2返回值
返回的是目的地的指针,类型是void *
2.使用样例
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char arr1[] = "iloveapple";
char arr2[] = "whar";
char * p =(char*)memcpy(arr2, arr1, 4);
printf("%s\n", arr2);
printf("%s\n", p);
}
![](https://img-blog.csdnimg.cn/img_convert/de4265897badba2b4ccf96e08433ed4e.png)
tip:需要注意的是两点
拷贝的内容不能相互重叠,如果重叠应使用memmov
数字指的是字节数,在进行内存拷贝的时候我们需要计算好需要拷贝的总字节数,防止过小达不到目的,过大产生越界访问。
int arr3[5] = { 15,32,45,1000,45 };
int tmp=0;
memcpy(&tmp, arr3, 4);
printf("%d", tmp);
在小端机器中,把4改成1一样能够进行不完整但是准确的进行拷贝
![](https://img-blog.csdnimg.cn/img_convert/145762caedfca821e57f5e65cc9107fd.png)
3.memcpy的模拟实现
void* my_memcpy(void* des, void const* source, size_t num)
{
assert(des&& source);
void* ret = des;
int i = 0;
for (i = 0; i < num;i++)
{
*((char*)des + i) = *((char*)source + i);
}
return ret;
}