面试:C/C++常见库函数实现

500次阅读  |  发布于4年以前

1、void* mymemcpy(void *dest, const void* src, size_t n);

内存拷贝函数,memcpy函数的功能是从源src所指的内存地址的起始位置开始拷贝n个字节到目标dest所指的内存地址的起始位置中

void* memcpy(void* dest,void* src,size_t n){
    assert(dest != NULL && src != NULL);

    if(src < dest && (char*)src + n > dest){
        char* pdst = (char*)dest+n-1;
        char* psrc = (char*)src+n-1;
        while(n--){
            *pdst-- = *psrc--;
        }
    }else{
        char* pdest = (char*)dest;
        char* psrc = (char*)src;
        while(n--){
            *pdest++ = *psrc++;
        }
    }
    return dest;
}

2、void *memset(void *s, int c, size_t n);

void* memset(void* src,int c,size_t n){
    assert(src != NULL);
    char* psrc = (char*)src;
    while(n--){
        *psrc++ = (char)c;
    }
    return src;
}

3、char* strcpy(char* dest,const char* src);

char* strcpy(char* dest,const char* src){
    assert(dest != NULL && src != NULL);

    size_t n = strlen(src);
    if(src < dest && src + n > dest){
        char* pdst = dest + n;
        *pdst-- = '\0';
        src = src + n - 1;
        while(n--){
            *pdst-- = *src--;
        }
    }else{
        char* pdst = dest;
        while((*pdst++ = *src++) != 0);
    }
    return dest;
}

4、char* mystrncpy(char* dest,char* src,size_t n);

char* strncpy(char* dest,const char* src,size_t n){
    assert(dest != NULL && src != NULL);

    if(src < dest && src + n > dest){
        int m = strlen(src) < n ? strlen(src):n;
        char* pdst = dest+m;
        *pdst-- = '\0';
        src = src + m-1;
        while(m--){
            *pdst-- = *src--;
        }
    }else{
        char* pdst = dest;
        size_t i = 0;
        while(i++ < n && (*pdst++ = *src++) != '\0');
        if(*(pdst-1) != '\0') *pdst = '\0';
    }
    return dest;
}

5、char* strcat(char* dest,const char* src)

char* strcat(char* dest,const char* src){
    assert(dest != NULL && src != NULL);
    char* pdst = dest;
    while(*pdst != '\0'){
        pdst++;
    }
    while((*pdst++ = *src++) != '\0');
    return dest;
}

6、int strcmp(const char* s1,const char* s2)

int strcmp(const char* s1,const char* s2){
    assert(s1 != NULL && s2 != NULL);
    while(s1 && s2 && *s1 == *s2){
        s1++;
        s2++;
    }
    return *s1 - *s2;
}

7、size_t strlen(const char* s)

size_t strlen(const char* src){
    assert(src != NULL);
    size_t ret = 0;
    while(*src++ != '\0'){
        ret++;
    }
    return ret;
}

链接:https://www.cnblogs.com/wxquare/p/5014445.html

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8