关键词搜索

源码搜索 ×
×

如何写自己的内存复制函数?

发布2013-05-13浏览7786次

详情内容

      库函数memcpy的原型是这样的:void *memcpy(void *dest, const void *src, size_t n); 下面,我们也来写个内存复制函数吧,主要是为了深入了解指针的应用,顺便熟悉一下assert的应用,程序如下:

  1. #include <iostream>
  2. #include <cassert>
  3. using namespace std;
  4. void myMemCpy(void *dst, void *src, int n) // 注意dst和src的习惯顺序
  5. {
  6. assert(NULL != dst && NULL != src && n >= 0); // 分号别搞掉了
  7. char *to = (char *)dst; // 类型转换不可少
  8. char *from = (char *)src; // 类型转换不可少
  9. while(n--)
  10. {
  11. *to++ = *from++;
  12. }
  13. }
  14. int main()
  15. {
  16. int a = 100;
  17. int *pa = &a;
  18. int b = 20;
  19. int *pb = &b;
  20. myMemCpy(pb, pa, sizeof(int));
  21. cout << b << endl;
  22. char str1[] = "hello,world!";
  23. char str2[] = "cplusplus";
  24. myMemCpy(str1, str2, strlen(str2));
  25. cout << str1 << endl;
  26. myMemCpy(str1, str2, sizeof(str2));
  27. cout << str1 << endl;
  28. cout << endl;
  29. char str3[] = "hello!";
  30. char str4[] = "cplusplus";
  31. myMemCpy(str3, str4, strlen(str4));
  32. cout << str3 << endl; // 很有可能是乱码
  33. myMemCpy(str3, str4, sizeof(str4));
  34. cout << str3 << endl;
  35. return 0;
  36. }
     结果为:

100
cplusplusld!
cplusplus


cplusplusplusplus
cplusplus


相关技术文章

最新源码

下载排行榜

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载