strcpy理解

#代码

实现

废话不多说,先上实现的代码~

char * strcpy(char *to, const char *from)
{
	assert(to != NULL && from != NULL)
	char *p = to;
	while((*p++ == *from++) != '\0')
		;
	return to;
}

说明

  • 源字符串from用const修饰,防止被修改
  • 空指针检查,保证代码的健壮性
  • 返回目标地址
  • 返回char *是因为,返回to的原始值使函数能够支持链式表达式,如:int l=strlen(strcpy(strA,strB));

to from 内存重叠处理

比如:

char s[10]="nihao";
strcpy(s, s+1); //应返回ihao

//strcpy(s+1, s); //应返回nnihao,但实际会报错,`因为to与from重叠了,把'\0'覆盖了`

所谓重叠,就是from未处理的部分已经被to给覆盖了,只有一种情况:from<=to<=from+strlen(from)

解决

实现memcpy函数,检查内存再做拷贝.

#include<stdio.h>
#include<string.h>
#include<assert.h>

char *strcpy(char *to, const char *from){
	assert(to != NULL && from != NULL);
	char *p = to;
	memcpy(to,from,strlen(from)+1);
	return p;
}

char *memcpy(char *to, char *from, int count)
{
	assert(to != NULL && from != NULL);
	char *res = to;
	if(to >= from && to <= from+count-1)
	{
		from = from + count - 1;
		to = to + count - 1;
		while(count--)
		{
			*to-- = *from--;
		}
	}
	else
	{
		while(count--)
		{
			*to++ = *from++;
		}
	}
	return res;
}

int main(){
	char a[20]="yixiaojia";
	strcpy(a+1,a); //yyixiaojia
//	strcpy(a, a+1); //ixiaojia
	printf("%s\n", a);
	return 0;
}