调用函数实现内存拷贝以及手动使用下标法和指针法实现内存拷贝 ------ memcpy

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<memory.h>
 4 
 5 
 6 void * indexmemcpy(void * _Dst,const void * _Src, unsigned int _Size);// 下标法自己实现内存拷贝
 7 void * pointmemcpy(void * _Dst, const void * _Src, unsigned int _Size);// 指针法自己实现内存拷贝
 8 
 9 void main()
10 {
11     // memccpy 实现数组拷贝
12 
13     int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };// 定义一个一维数组数组
14     int *p = malloc(sizeof(int)* 10);// 开辟一片内存接收拷贝
15     memcpy(p, a, 40); // 第一个是地址,被拷贝进去的内存地址 a是用于复制的内存首地址 40 是长度
16     for (int i = 0; i < 10;i++)
17     {
18         printf("%4d",p[i]);
19     }
20 
21     // memcpy 实现字符串拷贝
22 
23     char str[1024] = "Hello World!";
24     char *pstr = malloc(sizeof(char)*(strlen(str)+1));// 分配内存 加 1 处理'\0'
25     pstr = memcpy(pstr, str, strlen(str) + 1);
26     printf("\n%s",pstr);
27 
28     // 自己动手实现memcpy 内存拷贝
29 
30     indexmemcpy(pstr, str, strlen(str) + 1);
31     printf("\n%s", pstr);
32 
33     pointmemcpy(pstr, str, strlen(str) + 1);
34     printf("\n%s", pstr);
35     system("pause");
36 }
37 
38 // 下标法  自己实现内存拷贝
39 void * indexmemcpy(void * _Dst, const void * _Src, unsigned int _Size)
40 {
41     if (_Dst==NULL || _Src==NULL)
42     {
43         return NULL;
44     }
45 
46     char *ndest = _Dst;// 实现指针类型转换
47     char *src = _Src;// 实现指针类型转换
48 
49     for (int i = 0; i < _Size;i++)
50     {
51         ndest[i] = src[i];// 实现循环拷贝
52     }
53 
54     return ndest;
55 }
56 
57 // 指针法 自己实现内存拷贝
58 void * pointmemcpy(void * _Dst, const void * _Src, unsigned int _Size)
59 {
60     if (_Dst==NULL ||  _Src==NULL)
61     {
62         return NULL;
63     }
64 
65     int i = 0;
66     for (char *dest = _Dst, *src = _Src; i < _Size;dest++,src++,i++)
67     {
68         *dest = *src;
69     }
70     return _Dst;
71 }

 

posted on 2015-05-12 10:58  Dragon-wuxl  阅读(205)  评论(0)    收藏  举报

导航