如何写自己的内存复制函数?
2013-05-13 22:04
218 查看
库函数memcpy的原型是这样的:void *memcpy(void *dest, const void *src, size_t n); 下面,我们也来写个内存复制函数吧,主要是为了深入了解指针的应用,顺便熟悉一下assert的应用,程序如下:
#include <iostream>
#include <cassert>
using namespace std;
void myMemCpy(void *dst, void *src, int n) // 注意dst和src的习惯顺序
{
assert(NULL != dst && NULL != src && n >= 0); // 分号别搞掉了
char *to = (char *)dst; // 类型转换不可少
char *from = (char *)src; // 类型转换不可少
while(n--)
{
*to++ = *from++;
}
}
int main()
{
int a = 100;
int *pa = &a;
int b = 20;
int *pb = &b;
myMemCpy(pb, pa, sizeof(int));
cout << b << endl;
char str1[] = "hello,world!";
char str2[] = "cplusplus";
myMemCpy(str1, str2, strlen(str2));
cout << str1 << endl;
myMemCpy(str1, str2, sizeof(str2));
cout << str1 << endl;
cout << endl;
char str3[] = "hello!";
char str4[] = "cplusplus";
myMemCpy(str3, str4, strlen(str4));
cout << str3 << endl; // 很有可能是乱码
myMemCpy(str3, str4, sizeof(str4));
cout << str3 << endl;
return 0;
} 结果为:
100
cplusplusld!
cplusplus
cplusplusplusplus
cplusplus
#include <iostream>
#include <cassert>
using namespace std;
void myMemCpy(void *dst, void *src, int n) // 注意dst和src的习惯顺序
{
assert(NULL != dst && NULL != src && n >= 0); // 分号别搞掉了
char *to = (char *)dst; // 类型转换不可少
char *from = (char *)src; // 类型转换不可少
while(n--)
{
*to++ = *from++;
}
}
int main()
{
int a = 100;
int *pa = &a;
int b = 20;
int *pb = &b;
myMemCpy(pb, pa, sizeof(int));
cout << b << endl;
char str1[] = "hello,world!";
char str2[] = "cplusplus";
myMemCpy(str1, str2, strlen(str2));
cout << str1 << endl;
myMemCpy(str1, str2, sizeof(str2));
cout << str1 << endl;
cout << endl;
char str3[] = "hello!";
char str4[] = "cplusplus";
myMemCpy(str3, str4, strlen(str4));
cout << str3 << endl; // 很有可能是乱码
myMemCpy(str3, str4, sizeof(str4));
cout << str3 << endl;
return 0;
} 结果为:
100
cplusplusld!
cplusplus
cplusplusplusplus
cplusplus
相关文章推荐
- 类的各种成员函数在内存中是如何分配的?
- 自己写的几个ARM汇编内存操作函数
- 如何使用Fread和Fwrite写一个复制文件的函数
- 关于如何提取代码成为函数,自己浅薄的一些看法
- 如何使用composer的autoload来自动加载自己编写的函数库与类库
- c语言如何实现内存复制
- 多线程 DLL 回调函数问题,当应用程序退出时,有些操作并未完成,造成程序内存泄露,如何解决呢
- . 有一个一维数组,里面存储整形数据,请写一个函数,将他们按从大到小的顺序排列,要求执行效率高,并说明如何改善执行效率(该函数必须自己实现,不能使用php函数)。
- 如何用VB编写自己的DLL文件,并调用其中的函数
- 自己写的几个ARM汇编内存操作函数
- Delphi中复制带有String的记录结构时不能使用Move之类的内存操作函数
- android 如何判断开机完成并添加自己的函数处理
- memmove函数如何考虑内存重叠的
- C++实现内存复制函数(memmove解决内存重叠)
- 多线程之如何构造自己的barrier函数?(七)
- 自己实现strcpy字符串复制函数
- 如何查找(复制or下载)自己需要的文档(包括度娘的)
- linux性能分析及调优__cpu 性能瓶颈调优可调性能参数 、内存性能瓶颈可调性能参数(操作系统设置swap的目的、在写程序时、如何使自己的内存不被换出swap,常驻物理内存)、磁盘I/O可调性能参
- 如何使用 hive建立自己的函数在CLI界面上并使用
- 面试:实现内存复制函数