數據結構: 字符串2

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;
}
相關文章
相關標籤/搜索