1.描述
- void * memcpy ( void * destination, const void * source, size_t num );
- 返回值,参数指针类型为void*,失败也返回目的地址的头指针
- 按字节拷贝,源地址内容不可改,实际可能会被改。
- 没有严格的安全检查,空指针,以及重叠问题,越界访问。
2.代码展示
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
void* mymemcpy(void* dst,const void* src,size_t num)
{
assert(dst&&src);
unsigned char* pdst = (unsigned char*)dst;
unsigned char* psrc = (unsigned char*)src;
int lend = sizeof(pdst) / sizeof(pdst[0]);
int lens = sizeof(psrc) / sizeof(psrc[0]);
if ((pdst >= psrc && pdst < psrc + num)
|| (pdst < psrc&&psrc < pdst + num))
return NULL;
else
{
for (size_t i = 0; i < num; ++i)
{
pdst[i] = psrc[i];
}
return pdst;
}
}
void test6()
{
int arr1[10] = { -1,0,1,4,5};
int arr2[5] = { 255,127,8,9,10 };
memcpy(arr1, arr2, 100);
mymemcpy(arr1, arr2, 4);
for (int i = 0; i < sizeof(arr1) / sizeof(arr1[0]); ++i)
{
printf("%d ", arr1[i]);
}
char str1[] = "hello xff";
char str2[] = { 'w','o','r','l','d' };
void* ret1 = memcpy(str1, str2, 5);
printf("%s %p\n", str1, ret1);
void* ret2 = (char*)mymemcpy(str1, str2, 5);
printf("%s %p\n", str1, ret2);
}
int main()
{
test6();
system("pause");
return 0;
}
3.结果展示