1.按1个字节拷贝
(1)不要直接使用形参,要转换成char*
(2)目标地址要实现保存
(3)要考虑源和目标内存重叠的情况
void * mymemcpy(void *dest, const void *src, size_t count) { if (dest == NULL || src == NULL) return NULL; char *pdest = static_cast <char*>(dest); const char *psrc = static_cast <const char*>(psrc); int n = count; if (pdest > psrc && pdest < psrc+count) { for (size_t i=n-1; i != -1; --i) { pdest[i] = psrc[i]; } } else { for (size_t i= 0; i < n; i++) { pdest[i] = psrc[i]; } } return dest; }
2.按4个字节拷贝
(1)转成int*,按照每次4个字节来拷贝,不足四个字节的按一个字节拷贝
void *mymemcpy(void *dst,const void *src,size_t num) { assert((dst!=NULL)&&(src!=NULL)); int wordnum = num/4;//计算有多少个32位,按4字节拷贝 int slice = num%4;//剩余的按字节拷贝 int * pintsrc = (int *)src; int * pintdst = (int *)dst; while(wordnum--)*pintdst++ = *pintsrc++; while (slice--)*((char *)pintdst++) =*((char *)pintsrc++); return dst; }