以下是对memcpy函数的重写:
mymemcpy();使用的是下标法,pmemcpy();使用的是指针法。
#include<stdio.h>
#include<stdlib.h>
#include<memory.h>
#include<string.h>
/* 下标法 */
void * mymemcpy(void * _Dst, const void * _Src, size_t _Size)
{
if (_Dst == NULL || _Src == NULL)
{
return NULL;
}
/* 为什么要转换类型,类型决定步长 */
char *pdst = _Dst; /* 类型转换,为什么转成 char*? 因为数据在内存是以字节为单位的,所以这样具有通用性 */
char *psrc = _Src;
for (int i = 0; i < _Size; i++)
{
*pdst = *psrc;
pdst++;
psrc++;
}
return _Dst;
}
/* 指针法 */
void * pmemcpy(void * _Dst, const void * _Src, size_t _Size)
{
if (_Dst == NULL || _Src == NULL)
{
return NULL;
}
// int i = 0;
// for (char *pdst = _Dst, *psrc = _Src; i < _Size; pdst++,i++)
for (char *pdst = _Dst, *psrc = _Src; psrc < ((char *)_Src) + _Size; pdst++) // 注意下: psrc < ((char *)_Src) + _Size; 这个条件,要对 应前后的变量
{
*pdst = *psrc;
psrc++;
}
return _Dst;
}
void main()
{
int a[5] = { 1, 2, 3, 4, 5 };
int *p = malloc(sizeof(int)* 5);
//memcpy(p, a, 40);
//mymemcpy(p, a, 40);
pmemcpy(p, a, 40);
for (int i = 0; i < 5; i++)
{
printf("%3d", p[i]);
}
printf("\n");
char str[10] = "shanghai";
char *pstr = malloc(sizeof(char)*(strlen(str) + 1)); //+1:是因为 strlen();只计算字符,不算 \0 在内。
//memcpy(pstr, str, strlen(str) + 1);
//mymemcpy(pstr, str, strlen(str) + 1);
pmemcpy(pstr, str, strlen(str) + 1);
printf("%s\n", pstr);
system("pause");
}