memmove(内存拷贝函数)模拟实现

it2026-10-10  2

●内存拷贝函数memmove模拟实现 (操作的基本单位是字节,对类型不关心) memmove本为标准库中的函数,现人为的实现其功能; 根据拷贝的地址大小的不同,分为从右向左拷贝和从左向右拷贝两种拷贝方式 代码如下: void *my_memmove(void *dst,const void *src,size_t num) { assert(dst!=NULL); assert(src!=NULL); //根据所拷贝的字符串的位置分为两种情况: //src的地址小于dst的地址和src的地址大于dst的地址 if( dst>src&&dst<src+num) { //类型根据具体的情况进行设置 const char*src_=(char*)src+num-1; char*dst_=(char*)dst+num-1; //从右向左进行拷贝 while(num>0) { *dst_=*src_; dst_--; src_--; num--; } } else { const char*src_=(char*)src; char*dst_=(char*)dst; //从左向右进行拷贝 while(num>0) { *dst_=*src_; dst_++; src_++; num--; } } } int main() { char dst[32]="asdfghjkl"; int len=strlen(dst); my_memmove(dst,dst+3,len); printf("%s",dst); return 0; }
最新回复(0)