# include<stdio.h>
# include<stdlib.h>
# include<string.h>
char *myStrcpy1(char *dest, char *src){
char *d = dest;//参数备份
char *s = src;
int count = 0;
assert(dest);//检查参数合法性
assert(src);
if(src == dest){
return src;
}
count=strlen(src) + 1;
if(count <= 1)
return 0;
if(dest<src || dest >= (src+count)){
while(count--){
*d++ = *s++;
}
}else{//考虑内存地址重叠的情况。从末尾字符开始复制;
d = dest + count;
s = src + count;
while(count--){
*d-- = *s--;
}
}
return dest;
}
char * strcpy2(char *dest, char *src){
char * p = dest;
while(*src != '\0'){
*dest++ = *src++;
}
*dest = '\0';
return p;
}
assert((dest != NULL) &&(src != NULL));
char *p = dest;
while((*dest++ = *src++)!='\0')
NULL;
return p;
}
int main(){
char *s = "abcdef";
char d[512];
char *p = myStrcpy(d,s);
printf("%s",p);
return 0;
}
# include<stdlib.h>
# include<string.h>
# include <assert.h>
char *myStrcpy1(char *dest, char *src){
char *d = dest;//参数备份
char *s = src;
int count = 0;
assert(dest);//检查参数合法性
assert(src);
if(src == dest){
return src;
}
count=strlen(src) + 1;
if(count <= 1)
return 0;
if(dest<src || dest >= (src+count)){
while(count--){
*d++ = *s++;
}
}else{//考虑内存地址重叠的情况。从末尾字符开始复制;
d = dest + count;
s = src + count;
while(count--){
*d-- = *s--;
}
}
return dest;
}
char * strcpy2(char *dest, char *src){
char * p = dest;
while(*src != '\0'){
*dest++ = *src++;
}
*dest = '\0';
return p;
}
//这里有三个需要注意的地方,第一个就是断言宏assert的使用assert。就是要求里面的条件都是真的,在运行过程中,如果assert 的参数为假,那么程序就会中止
//while( (*strDest++ = * strSrc++) != ‘/0’ ) NULL ; 这里++运算符优先级较*高,而且这个里面隐式包含了将'/0'赋值给字符串最后
//strcpy 能把strSrc 的内容复制到strDest,为什么还要char * 类型的返回值?这是为了实现链式表达式。 所谓链式表达式就是可以将strcpy函数作为其他函数的参数。
例如 int length = strlen( strcpy( strDest, “hello world”) );
assert((dest != NULL) &&(src != NULL));
char *p = dest;
while((*dest++ = *src++)!='\0')
NULL;
return p;
}
int main(){
char *s = "abcdef";
char d[512];
char *p = myStrcpy(d,s);
printf("%s",p);
return 0;
}