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

时间:2023-03-10 07:19:57
面试:C/C++常见库函数实现

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-;
char* psrc = (char*)src+n-;
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 - ;
while(n--){
*pdst-- = *src--;
}
}else{
char* pdst = dest;
while((*pdst++ = *src++) != );
}
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-;
while(m--){
*pdst-- = *src--;
}
}else{
char* pdst = dest;
size_t i = ;
while(i++ < n && (*pdst++ = *src++) != '\0');
if(*(pdst-) != '\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 = ;
while(*src++ != '\0'){
ret++;
}
return ret;
}