首页 > 技术文章 > strcpy自实现

luntai 2016-09-30 20:47 原文

  为了避免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;
}

 

推荐阅读