1

strcpy

/*prototype to write a correct code in c language*/

/*源字符串参数用const修饰,防止修改源字符串*/
char* strcpy_(char* des, const char* src) {
    /*边界检查*/
    assert(des != NULL && src != NULL);
   
    char* ret = des;
    
    /* 保证复制'\0' */
    while ((*des++ = *src++) != '\0');
   
    return ret;
}
/*take memory overlapping into consideration*/
/* 当出现内存重叠且src的起始地址低于des起始地址时,需要从后往前拷贝*/
char* strcpy2_(char* des, const char* src) {
    assert(des != NULL && src != NULL);
   
    int src_size = strlen(src) + 1;
   
    char* ret = des;
   
    if (src < des && src + src_size > des) {
        des = des + src_size - 1;
        src = src + src_size - 1;
        while (src_size--) {
            *des-- = *src--;
        }
    } else {
        /* destination can be ahead of source */
       while ((*des++ = *src++) != '\0');
    }

    return ret;
}

shiyang6017
158 声望59 粉丝