首页 > 代码库 > strcpy自实现

strcpy自实现

  为了避免strcpy源串覆盖问题(P220),自实现strcpy。

#include <stdio.h>#include <string.h>#include <assert.h>#include <malloc.h>void myStrcpy(char *to, char *from){    assert(to != NULL && from != NULL);    while(*from != \0){        *to ++ = *from ++;    }    *to = \0;}int main(){    char s[] = "123456789";    char d[] = "1234";    printf("&s= %x, &d= %x\n",s,d);    //在栈空间上,d的起始地址在s的起始地址之前。    strcpy(d, s);    //使用strcpy将会对源串s产生覆盖    printf("s=%s d=%s\n",s,d);    char *str = (char*)malloc(15 * sizeof(char*));    char *ttr = (char*)malloc(15 * sizeof(char*));    myStrcpy(str, "123456789");    myStrcpy(ttr, "1234");    myStrcpy(ttr, str);    printf("str=%s ttr=%s\n",str,ttr);    return 0;}

 

strcpy自实现