调用函数实现字节拷贝以及手动使用下标法和指针法实现 ------ _memccpy
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 5 /* 6 函数名: _memccpy 7 功 能: 从源source中拷贝n个字节到目标destin中,遇到字符 ch 就提前结束; 8 用 法: void *memccpy(void *destin, void *source, unsigned char ch,unsigned n); 9 */ 10 11 void * indexmemccpy(void * _Dst,const void * _Src,int _Val, size_t _MaxCount);// 手动使用下标法实现memccpy函数 12 13 void * pointmemccpy(void * _Dst, const void * _Src, int _Val, size_t _MaxCount);// 手动使用指针法实现memccpy函数 14 15 void main() 16 { 17 char str[100] = "This is the source string"; 18 char *pstr = (char[128]){ 0 }; 19 _memccpy(pstr, str, 'e', 30);// 拷贝30个字符 遇到字符 'e' 就提前结束 20 printf("%s\n",pstr); 21 22 // 调用手动实现的下标法 23 indexmemccpy(pstr, str, 'e', 30); 24 printf("%s\n", pstr); 25 26 // 调用手动实现的指针法 27 pointmemccpy(pstr, str, 'e', 30); 28 printf("%s\n", pstr); 29 30 system("pause"); 31 } 32 33 34 // 手动使用下标法实现memccpy函数 35 void * indexmemccpy(void * _Dst, const void * _Src, int _Val, size_t _MaxCount) 36 { 37 char *dst = _Dst; 38 char *src = _Src; 39 40 for (int i = 0; i < _MaxCount;i++) 41 { 42 dst[i] = src[i]; 43 if (dst[i]==_Val) 44 { 45 break; 46 } 47 /* 48 49 if ((dst[i] = src[i]) == _Val) // 写法二 50 { 51 break; 52 } 53 54 */ 55 56 } 57 } 58 59 // 手动使用指针法实现memccpy函数 60 void * pointmemccpy(void * _Dst, const void * _Src, int _Val, size_t _MaxCount) 61 { 62 char *dst = _Dst;// 指针转换 63 char *src = _Src;// 指针转换 64 int i = 0; 65 while (i<_MaxCount)// 控制循环 66 { 67 *dst = *src; // 给指向的字符 赋值 68 if (*dst==_Val) 69 { 70 break; 71 } 72 dst++; 73 src++; 74 i++; 75 76 /* 77 if ((*dst++ = *src++) == _Val)// 写法二 78 { 79 break; 80 } 81 i++; 82 */ 83 84 } 85 } 86 /*****************************运行结果*****************************/ 87 /* 88 This is the 89 This is the 90 This is the 91 请按任意键继续. . . 92 */
长风破浪会有时,直挂云帆济沧海
posted on 2015-05-13 09:02 Dragon-wuxl 阅读(154) 评论(0) 收藏 举报
浙公网安备 33010602011771号