您的位置:首页 > 其它

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

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐