void*
MemCpy_(void* dst ,const void* src ,size_t size);
实现该函数,
并对比实现Strcpy
字符串拷贝。 1 void* MemCpy_(void* dst ,const void* src ,size_t size)
2 {
3 assert(dst && src);
4 char *pdst;
5 char *psrc;
6 if (src < dst &&((char*)src + size >
7 (char*)dst))
8 {
9 psrc = (char *)src + size - 1;
10 pdst = (char *)dst + size - 1;
11
12 while(size--){
13 *pdst-- = *psrc--;
14 }
15 }else{
16 psrc = (char *)src;
17 pdst = (char *)dst;
18
19 while(size--){
20 *pdst++ = *psrc++;
21 }
22 }
23 return dst;
24 }
25
26 void* StrCpy_(char* strDst ,const char* strSrc)
27 {
28 assert(strSrc && strDst);
29 char *strCopy = strDst;
30 while(*strSrc)
31 {
32 *strDst++ = *strSrc++;
33 }
34 return strCopy;
35 }
36
37 char* str = "TestAbcdefg";
38 //测试程序
39 char strArray[] = "TestAbcdefg";
40 char buf[15] = {0};
41 //str[1] = 'X'; runtime error
42 strArray[1] = 'B';
43 cout<<str<<endl;
44 cout<<strArray<<endl;
45 MemCpy_(strArray ,strArray + 3 ,4);
46 cout<<strArray<<endl;
47 StrCpy_(buf ,str);
48 cout<<buf<<endl;
49