标签:set class pre int strlen 强制 over 库函数 logs
内存拷贝函数,memcpy函数的功能是从源src所指的内存地址的起始位置开始拷贝n个字节到目标dest所指的内存地址的起始位置中
1 void *mymemcpy(void *dest, const void* src, size_t n) { 2 assert(dest != NULL && src != NULL); 3 4 //考虑内存重叠 5 if (src < dest && (char*) src + n > dest) { 6 7 //void*类型强制转换为char* 8 char* psrc = (char*) src + n - 1; 9 char* pdst = (char*) dest + n - 1; 10 11 while (n--) { 12 *pdst-- = *psrc--; 13 } 14 } else { 15 char* psrc = (char*) src; 16 char* pdst = (char*) dest; 17 while (n--) { 18 *pdst++ = *psrc++; 19 } 20 } 21 return dest; 22 }
void *memset(void *s, int ch, size_t n);
1 void* mymemset(void* s, int c, size_t n) { 2 if (s == NULL) return NULL; 3 char* ps = (char*) s; 4 while (n--) { 5 *ps++ = (char) c; 6 } 7 return s; 8 }
1 char* mystrcpy(char* dest, const char* src) { 2 if (dest == NULL || src == NULL) return NULL; 3 4 int n = strlen(src); 5 //memory overlap 6 if (src < dest && src + n > dest) { 7 char* pdst = dest + n; 8 char* psrc = const_cast<char*>(src) + n; 9 *pdst-- = *psrc--; 10 while (n--) { 11 *pdst-- = *psrc--; 12 } 13 } else { 14 char* pdst = dest; 15 while ((*pdst++ = *src++) != ‘\0‘) 16 ; 17 } 18 return dest; 19 }
1 char* mystrncpy(char* dest, char* src, size_t n) { 2 if (dest == NULL || src == NULL) 3 return NULL; 4 5 if (src < dest && src + n > dest) { 6 char* pdst = dest + n - 1; 7 char* psrc = src + n - 1; 8 *(pdst + 1) = ‘\0‘; 9 while (n--) { 10 *pdst-- = *psrc--; 11 } 12 } else { 13 char* pdst = dest; 14 while (n--) { 15 *pdst++ = *src++; 16 } 17 *pdst = ‘\0‘; 18 } 19 return dest; 20 }
1 char* mystrcat(char* dest, const char* src) { 2 if (dest == NULL || src == NULL) 3 return NULL; 4 5 int n = strlen(src); 6 char* pdst = dest; 7 while (*pdst != ‘\0‘) { 8 pdst++; 9 } 10 while (n--) { 11 *pdst++ = *src++; 12 } 13 pdst = ‘\0‘; 14 return dest; 15 }
1 int mystrcmp(const char* s1, const char* s2) { 2 assert(s1 != NULL && s2 != NULL); 3 while (s1 && s2 && *s1 == *s2) { 4 s1++; 5 s2++; 6 } 7 return *s1 - *s2; 8 }
1 int mystrlen(const char* s) { 2 assert(s != NULL); 3 int len = 0; 4 while (*s++ != ‘\0‘) { 5 len++; 6 } 7 return len; 8 }
标签:set class pre int strlen 强制 over 库函数 logs
原文地址:http://www.cnblogs.com/wxquare/p/5014445.html