2012年(134)
分类:
2012-04-08 15:49:22
原文地址:strcpy和memcpy的标准实现 作者:yulianliu1218
//============================================================================
// Name : HelloWorld.cpp
// Author : chio
// Copyright : Suprasoft Inc,.
// Description : TODO
//============================================================================
#include <iostream>
#include <string.h>
#include <cassert>
using namespace std;
char * strcpy(char *dst, const char *src) {
assert(src != NULL && dst != NULL);
char *ret = dst;
while((*dst++ = *src++) != '\0') ;
return ret;
}
void * memcpy(void *dst, const void *src, size_t len) {
assert(src != NULL && dst != NULL);
void *ret = dst;
int i = len;
//防重叠
if(src < dst) {
char *csrc = (char *)src;
char *cdst = (char *)dst;
while(i--) {
*cdst++ = *csrc++;
}
} else {
char *csrc = (char *)src + len - 1;
char *cdst = (char *)dst + len - 1;
while(i--) {
*cdst-- = *csrc--;
}
}
return ret;
}
int main() {
char *src = "hello world";
char *dst = new char[0];
cout << strcpy(dst, src) << endl;
void *memsrc = (void *)"hello";
char memdst[6];
memdst[5] = '\0';
cout << (char *)memcpy(memdst, memsrc, 5) << endl;
return 0;
}