注:考虑内存重叠问题
#include "stdafx.h"
#include <iostream>
#include <assert.h>
char* myStrCpy(char *pDst, const char *pSrc)
{
assert(NULL != pDst);
assert(NULL != pSrc);
char *pDT = pDst;
size_t iCount = strlen(pSrc) + 1;
const char *pST = pSrc;
if (pDT <= pST || pDT >= (pST + iCount)) //源地址和目的地址不重叠,低字节向高字节拷贝
{
while (iCount--)
{
*pDT++ = *pST++;
}
}
else //源地址和目的地址重叠,高字节向低字节拷贝
{
pDT += iCount - 1;
pST += iCount - 1;
while (iCount--)
{
*pDT-- = *pST--;
}
}
return pDst;
}
int _tmain(int argc, _TCHAR* argv[])
{
char src[10] = "hellhelo";
char dst[10];
myStrCpy(src + 1, src);
std::cout << src;
getchar();
return 0;
}