//第一种
#include
#include
#include
void *my_memcpy(void *dest, const void *src, int count)
{
assert(dest);
//断言,判断此指针是否是空指针,因为空指针不能够解引用
assert(src);
//断言
int i = 0;
char *pdest = (char *)dest;
//强制转换(因为count是字节的个数,所以写为char更为方便)
char *psrc = https://www.it610.com/article/(char *)src;
//强制转换
for (i = 0;
i < count;
i++)
{
*pdest++ = *psrc++;
}
return dest;
//返回目标空间的起始地址
}
void Show(int *arr2, int *arr1,int sz)
{
int i = 0;
for (i = 0;
i < sz;
i++)
{
printf("%d ", arr2[i]);
}
printf("\n");
}
int main()
{
int arr1[10] = { 0,1, 2, 3, 4, 5, 6, 7, 8, 9 };
int arr2[10] = { 0 };
int sz = sizeof(arr1) / sizeof(arr1[0]);
my_memcpy(arr2, arr1,sizeof(arr1));
//内存拷贝函数
Show(&arr2, &arr1,sz);
//显示数组arr2元素的函数
system("pause");
return 0;
}
//第二种
#include
#include
#include
void *my_memcpy(void *dest, const void *src, int count)
{
void *ret = dest;
assert(dest);
//断言,判断此指针是否是空指针,因为空指针不能够解引用
assert(src);
//断言
int i = 0;
for (i = 0;
i < count;
i++)
{
*(char *)dest = *(char *)src;
//强制类型转换后,并解引用
dest = (char *)dest + 1;
//实现 dest++,但之前需要强制类型转换
src = https://www.it610.com/article/(char *)src + 1;
//实现 src++,但之前需要强制类型转换
}
return ret;
//返回目标空间的起始地址
}
void Show(int *arr2, int *arr1, int sz)
{
int i = 0;
for (i = 0;
i < sz;
i++)
{
printf("%d ", arr2[i]);
}
printf("\n");
}
int main()
{
int arr1[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int arr2[10] = { 0 };
int sz = sizeof(arr1) / sizeof(arr1[0]);
my_memcpy(arr2, arr1, sizeof(arr1));
//内存拷贝函数
Show(&arr2, &arr1, sz);
//显示数组arr2元素的函数
system("pause");
return 0;
}
【C|模拟实现memcpy函数(内存拷贝函数)】void *:可以接收任何类型的参数