C语言之memcpy函数
导读:本文共11674.5字符,通常情况下阅读需要39分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 昨天自己动手实现memcpy这个函数,用一个例程试了一下,结果正确,满心欢心,可是有些地方想不明白,于是百度了一下,结果自己写的函数简直无法直视。觉得还是写个总结,以示教训。先贴上我自己的函数:[cpp]view plaincopychar*mymemcpy(char*dest,constchar*src,intn){char*pdest;char*psrc;p... ...
目录
(为您整理了一些要点),点击可以直达。[cpp]view plaincopy
char*mymemcpy(char*dest,constchar*src,intn)
{
char*pdest;
char*psrc;
pdest=dest;
psrc=src;
for(n;n>0;n--)
{
*pdest=*psrc;
pdest++;
psrc++;
}
}
[cpp]view plaincopy
#include<stdio.h>
void*memcpy(void*dest,constvoid*src,size_tcount)
{
<spanstyle="white-space:pre"></span>if(NULL==dest||NULL==src||count<=0)
<spanstyle="white-space:pre"></span>returnNULL;
<spanstyle="white-space:pre"></span>while(count--)
<spanstyle="white-space:pre"></span>*dest++=*src++;
<spanstyle="white-space:pre"></span>returndest;
}
[cpp]view plaincopy
<prename="code"class="cpp">#include<stdio.h>
void*memcpy(void*dest,constvoid*src,size_tcount)
{
if(NULL==dest||NULL==src||count<=0)
returnNULL;
while(count--)
*(char*)dest++=*(char*)src++;
returndest;
}
[cpp]view plaincopy
void*memcpy(void*dest,constvoid*src,intcount)
{
<spanstyle="white-space:pre"></span>void*ptr=dest;
<spanstyle="white-space:pre"></span>if(NULL==dest||NULL==src||count<=0)
<spanstyle="white-space:pre"></span>returnNULL;
<spanstyle="white-space:pre"></span>while(count--)
<spanstyle="white-space:pre"></span>*(char*)dest++=*(char*)src++;
<spanstyle="white-space:pre"></span>returnptr;
}
[cpp]view plaincopy
void*memcpy(void*dest,constvoid*src,unsignedintcount);
{
if((src==NULL)||(dest==NULL))
return;
while(count--)
*dest++=*src++;
returndest;
}
dest都指到哪里去了?怎么着也得备份一下dest的值,好让函数返回的指针是从头开始的
[cpp]view plaincopy
void*memcpy(void*dest,constvoid*src,size_tcount)
{
char*tmp=dest;
constchar*s=src;
while(count--)
*tmp++=*s++;
returndest;
}
能否改进? src和dest都强制转换成char*类型的指针,那么copy一定是一个字节一个字节的完成?那么第三版来了
[cpp]view plaincopy
void*memcpy(void*dst,constvoid*src,size_tnum)
{
intnchunks=num/sizeof(dst);/*按CPU位宽拷贝*/
intslice=num%sizeof(dst);/*剩余的按字节拷贝*/
unsignedlong*s=(unsignedlong*)src;
unsignedlong*d=(unsignedlong*)dst;
while(nchunks--)
*d++=*s++;
while(slice--)
*((char*)d++)=*((char*)s++);
returndst;
}
[cpp]view plaincopy
void*memcpy(void*dest,constvoid*src,size_tcount)
{
char*d;
constchar*s;
if(dest>(src+size))||(dest<src))
{
d=dest;
s=src;
while(count--)
*d++=*s++;
}
else/*overlap*/
{
d=(char*)(dest+count-1);/*offsetofpointerisfrom0*/
s=(char*)(src+count-1);
while(count--)
*d--=*s--;
}
returndest;
}
C语言之memcpy函数的详细内容,希望对您有所帮助,信息来源于网络。