现在的位置: 首页 > 综合 > 正文

strcpy函数与memcpy函数的区别及其函数实现

2013年09月22日 ⁄ 综合 ⁄ 共 637字 ⁄ 字号 评论关闭

先看函数实现:

显然两函数的原型都不一样:void *memcpy(void * ,const void * ,size_t )与char *strcpy(char * ,const char * );

void *memcpy(void *dst,const void *src,size_t count)
{
	if(dst==NULL || src==NULL)
		return NULL;
	
	if(cout<0)
		return NULL;

	char *pDst=(char *)dst;
	char *pSrc=(char *)src;

	if(pDst<pSrc && pDst+cout>pSrc)
	{
		size_t i=cout-1;
		while(i>=0)
		{
			pDst[i]=pSrc[i];
			i--;
		}
	}
	else
	{
		size_t i=0;
		while(i<cout)
		{
			pDst[i]=pSrc[i];
			i++;
		}
	}

	return dst;
}

char *strcpy(char *dst,const char *src)
{
	if(dst==NULL || src==NULL)
		return NULL;

	char *p=dst;
	while(*p++=*src++)
		;

	return dst;
}

1、函数的形参类型,个数返回值都不一样;

2、strcpy只能实现字符串的拷贝,以‘\0’作为结束标志,而memcpy可以拷贝很多类型,并以拷贝的字节数为拷贝结束标志;

3、memcpy有一定的处理内存覆盖问题能力,不过也不太好,而strcpy则无处理内存覆盖的能力。memmove()很好的处理内存覆盖。

抱歉!评论已关闭.