strcpy与memcpy重新实现

来源:互联网 发布:wpf 数据绑定 编辑:程序博客网 时间:2024/05/21 09:45
#include<iostream>#include<assert.h>using namespace std;//此版本并未考虑到内存重叠的情况char* strcpy_overwrite1(char*Des,char*Src){assert(Des!=NULL);assert(Src!=NULL);//assert的作用是现计算表达式 expression //如果其值为假(即为0),那么它先向stderr打印一条出错信息,然后通过调用 abort 来终止程序运行。char *Res=Des;while ((*Des++=*Src++)!='\0');return Res;}void * memcpy_overwrite(void *dst,const void *src,unsigned int count){assert(dst!=NULL);assert(src!=NULL);char*pdst;char*psrc;if (dst>src&&dst<((char*)src+count))//内存如果重叠冲后往前赋值{pdst=(char*)dst+count-1;//内型的转换psrc=(char*)src+count-1;while (count--){*pdst--=*psrc--;}}else{pdst=(char*)dst;//不重叠的psrc=(char*)src;while(count--){*pdst++=*psrc++;}}return dst;}char* strcpy_overwrite2(char*Des,char*Src){assert(Des!=NULL);assert(Src!=NULL);//assert的作用是现计算表达式 expression //如果其值为假(即为0),那么它先向stderr打印一条出错信息,然后通过调用 abort 来终止程序运行。//memcpy(Des,Src,strlen(Src)+1);memcpy_overwrite(Des,Src,strlen(Src));return Des;}int main(){char str[10]="123";//strcpy_overwrite1(str+1,str);//出错//strcpy(str+1,str);strcpy_overwrite2(str+1,str);cout<<str<<endl;return 0;}

0 0
原创粉丝点击