您的位置:首页 > 其它

strcpy和memcpy函数的实现

2015-04-29 15:10 176 查看
#include <cstdio>

char* strcpy1(char *des,const char *src)  //自己的
{
if(des== NULL || src== NULL)
return NULL;
char *pDes= des;
char *pSrc= (char*)src;
while((*pDes++= *pSrc++)!= '\0');
return pDes;
}

void* memcpy1(void *des, const void *src, unsigned int len) //自己的
{
if(des== NULL || src== NULL)
return NULL;
char *pDes= (char*)des;
char *pSrc= (char*)src;
if(pDes<= pSrc || pDes>= pSrc+ len)
{
while(len--)
*pDes++= *pSrc++;
}
else
{
pDes+= len- 1;
pSrc+= len- 1;
while(len--)
*pDes--= *pSrc--;
}
return des;
}

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;
}

int main()
{
char ch[20]="123";
char cc[20];
strcpy1(cc, ch);
printf("%s %s\n",cc,ch);
memcpy1(cc+3,ch,4);
printf("%s %s\n",cc,ch);
memcpy1(cc+1, cc, 7);
printf("%s\n",cc);
int a[]={1,2,3,4,5};
int b[20];
memcpy1(b, a, sizeof(int)*5);
//mymemcpy(b, a, sizeof(int)*5);
for(int i= 0; i< 5; i++)
printf("%d\n",b[i]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: