实现strcpy
/****************************************
*vs 2015测试成功
*如要考虑到dest的长度小于src,则需要判断条件
*邮箱 yqtao@whu.edu.cn
*欢迎交流
*****************************************/
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
char* mystrcpy(char* dest, const char* src)
{
//考虑条件
if (nullptr == dest || nullptr == src)
return nullptr;
char* start = dest;
while (*src)
{
*start = *src;
src++;
start++;
}
*start= '\0';
//简单写法,其中最后的已有\0了
//while ((*start++=*src++)!='\0');
return dest;
}
//测试代码
int main(int argc, char*argv)
{
char src[6] = { 'h','e','l','l','o'};
char *dest=new char[strlen(src) + 1];
cout << mystrcpy(dest, src) << endl;
delete[]dest;
dest = nullptr;
}
实现strcat
char* mystrcat(char* dest, const char* src)
{
char* start = dest;
while (*dest++);
dest--;//指向字符串的结束符
//可用dest=dest+strlen(dest)达到\0位置
while (*dest++ = *src++);//循环赋值
return start;
}
memcpy实现
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
//memcpy不仅仅能赋值char类型,size为赋值的个数
void* mymemcpy(void* dest, const void* src,size_t size)
{
if (dest == nullptr || src == nullptr)
return nullptr;
char *tempTo = (char*)dest;//保存首地址
char *tempFrom = (char*)src;
while (size-- > 0)
*tempTo++ = *tempFrom++;//赋值size个值
return dest;
}
int main(int argc, char*argv)
{
char src[6] = { 'h','e','l','l','o'};
char dest[20] = { 'i' };
mymemcpy(dest, src, 3);
cout << dest<< endl;
}