memcpy 使用和模拟实现
memcpy函数的概念
void * memcpy ( void * destination, const void * source, size_t num );
memcpy函数的使用
#include <stdio.h>
#include <string.h>
int main()
{
int arr1[] = { 0,1,2,3,4,5,6,7,8,9 };
int arr2[20] = { 0 };
//memcpy函数将arr1中前20个字节数据拷贝到arr2数组中
memcpy(arr2, arr1, 20);
printf("arr2:");
for (int i = 0; i < 20; i++)
{
printf("%d ", arr2[i]);
}
printf("\n");
return 0;
}
memcpy函数的模拟实现
//模拟实现
#include <stdio.h>
#include <string.h>
#include <assert.h>
my_memcpy(void* dest, const void* src, size_t num)
{
void* ret = dest;
assert(dest && src);
while (num--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
return ret;
}
int main()
{
int arr1[] = { 0,1,2,3,4,5,6,7,8,9 };
int arr2[20] = { 0 };
//memcpy函数将arr1中前20个字节数据拷贝到arr2数组中
my_memcpy(arr2, arr1, 20);
printf("arr2:");
for (int i = 0; i < 20; i++)
{
printf("%d ", arr2[i]);
}
printf("\n");
return 0;
}