41.内存函数实现(memcpy,memset,memmove,memicmp,memchr.memccpy)
- memcpy
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <memory.h> 4 5 void * mymemcpy(void* _Dst, void const* _Src, size_t _Size) 6 { 7 if (_Dst == NULL || _Src == NULL) 8 { 9 return NULL; 10 } 11 12 //转化成char类型,一次前进一个字节 13 char *dst = _Dst; 14 char *src = _Src; 15 16 for (int i = 0; i < _Size; i++) 17 { 18 dst[i] = src[i]; 19 } 20 21 return _Dst; 22 } 23 24 void main() 25 { 26 int a[10] = { 1,2,3,4,5,6,7,8,9,10 }; 27 int *p = malloc(sizeof(int) * 10); 28 int *tmp = mymemcpy(p, a, 40); 29 30 for (int i = 0; i < 10; i++) 31 { 32 printf("%d\n" ,p[i]); 33 } 34 35 char str[100] = "hello world"; 36 char mystr[100]; 37 mymemcpy(mystr, str, strlen(str) + 1); 38 39 printf("%s\n", mystr); 40 41 system("pause"); 42 }
- memset
1 void *mymemset(void *_Dst, int _Val, size_t _Size) 2 { 3 if (_Dst == NULL || _Val == NULL) 4 { 5 return; 6 } 7 8 for (int i = 0; i < _Size; i++) 9 { 10 ((char *)_Dst)[i] = _Val; 11 } 12 13 return _Dst; 14 }
- memmove
1 void * mymemmove(void *_Dst, const void *_Src, size_t _Size) 2 { 3 if (_Dst == NULL || _Src == NULL) 4 { 5 return NULL; 6 } 7 8 void *psrc = malloc(_Size);//分配内存 9 memcpy(psrc, _Src, _Size); 10 memcpy(_Dst, psrc, _Size); 11 free(psrc); 12 return _Dst; 13 }
- memicmp(比较指定字符串前n个字符串)
1 int mymemicmp(const void *_Buf1, const void *_Buf2, size_t _Size) 2 { 3 //保存变量 4 char *buf1 = _Buf1; 5 char *buf2 = _Buf2; 6 7 //结束标识 8 char *end = buf1 + _Size; 9 10 while ((*buf1 == *buf2) && buf1 != end) 11 { 12 buf1++; 13 buf2++; 14 } 15 16 if (buf1 == end) 17 { 18 return 0; 19 } 20 else 21 { 22 return *buf1 - *buf2 > 0 ? 1 : -1; 23 } 24 }
- memchr(寻找一个字符串中是否有指定字符)
1 void *mymemchr(void *start, char ch, int maxlength) 2 { 3 char *p = NULL; 4 for (int i = 0; i < maxlength; i++) 5 { 6 if (((char *)start)[i] == ch) 7 { 8 p = (char *)start + i; 9 break; 10 } 11 } 12 return p; 13 }
- memccpy(复制n个字符,遇到指定值退出)
1 void * mymemccpy(void * _Dst, const void *_Src, int _Val,size_t _MaxCount) 2 { 3 char *dst = _Dst; 4 char *src = _Src; 5 6 for (int i = 0; i < _MaxCount; i++) 7 { 8 dst[i] = src[i]; 9 if (dst[i] == _Val) 10 { 11 break; 12 } 13 } 14 }