一些面试基础知识点(2)

strcp strlcp memcp的实现,又写了一遍,也不知道是第几遍了。目标串的容量,字符串重叠,宽字符,四字节优化这些东西不考虑了。

 

char* strcp(char* dest, const char* src) {

    assert(dest != NULL);

    assert(src != NULL);

    if (dest == NULL || src == NULL) return NULL;



    char* save = dest;

    while((*dest++ = *src++) != '\0') {

    }



    return save;

}



size_t strlcp(char* dest, const char* src, size_t size) {

    assert(dest != NULL);

    assert(src != NULL);

    if (dest == NULL || src == NULL || size == 0) return 0;



    size_t size_ret = 0;

    size_t n = size;

    while((*dest++ = *src++) != '\0') {

        if (0 == --n) break;

        size_ret++;

    }

    dest--;

    *dest = '\0';



    return size_ret + 1;

}



void* memcpy(void* dest, void* src, size_t n) {

    assert(NULL != dest);

    assert(NULL != src);

    if (NULL == dest || NULL == src || 0 == n) return NULL;



    void* ret = dest;

    char* dest_temp = (char*) dest;

    char* src_temp = (char*) src;

    while (n--) {

        *dest_temp++ = *src_temp++;

    }

    return ret;

}



 

你可能感兴趣的:(面试)