C++ 之手写memcpy

#include<iostream>
#include<cstdio>
using namespace std;


void* mymemcpy(void* dst, const void* src, size_t n){
if (dst == NULL || src == NULL) return NULL;
char* pdst;
char* psrc;

if (src >= dst || (char*)dst >= (char*)src + n - 1){
pdst = (char*)dst;
psrc = (char*)src;

while (n--){
*pdst++ = *psrc++;
}
}
else{
pdst = (char*)dst+ n - 1;
psrc = (char*)src+ n - 1;

while (n--){
*pdst-- = *psrc--;
}
}

return dst;
}

 

int main(){

char buf[100] = "abcdefghijk";
memcpy(buf+2, buf, 5);
//mymemcpy(buf + 2, buf, 5);
printf("%s\n", buf + 2);

return 0;
}

 

结果 
abcdehijk

posted @ 2019-11-08 16:01  久龄  阅读(1000)  评论(0编辑  收藏  举报