C++实现常见库函数1

1. memcpy

内存拷贝函数 memcpy 的功能是从源 src 所指的内存地址的起始位置开始拷贝 n 个字节到目标 dst 所指的内存地址的起始位置开始的内存中。

2. memset

内存赋值函数 memset 用来给某一块内存空间进行赋值,为逐字节拷贝,是对较大的结构体或数组进行清零操作的一种最快方法,src 是起始地址,val 是要赋的值,n 是要赋值的字节数。

3. strcpy

字符串拷贝 strcpy 把 src 字符串拷贝到 dst,并返回 dest。

#include<iostream>
#include<cstring>
#include<assert.h>
using namespace std;


void* myMemcpy(void* dst, void* src, size_t len) {
	if (dst == NULL || src == NULL)
		return NULL;
	// assert(dst != NULL && src != NULL);
	// 判断参数是否有效

	char* tempDst = (char*)dst;
	char* tempSrc = (char*)src;
	// 定义 temp 指针存放源地址和目的地址(各自位置的起始地址)

	if (tempSrc > tempDst || tempSrc + len < tempDst) {
	// 两种情况下可以直接从前向后进行复制:
	//	(1)目的地址起始在源地址之前; (2)源地址起始在目的地址前且相差大于长度 len
		while (len--) {
			*tempDst = *tempSrc;
			tempDst++;
			tempSrc++;
			// 或者为 *tempDst++ = *tempSrc++; 
			// 先解除引用,再复制,最后将指针++移动到下一个位置
		}
	}
	else {
	// 其他情况需要从后向前复制以避免重叠情况,将 temp 指针移动到结尾再开始
		tempDst += len;
		tempSrc += len;
		while (len--) {
			*tempDst = *tempSrc;
			tempDst--;
			tempSrc--;
		}
	}
	return dst;
}


void* myMemset(void* src, int val, size_t n) {
	assert(src != NULL);
	char* tempSrc = (char*)src;
	while (n--)
		*tempSrc++ = (char) val;
	return src;
}


char* myStrcpy(char* dst, const char* src) {
	assert(dst != NULL && src != NULL);
	size_t n = strlen(src);
	char* tempDst = dst;
	if (dst < src || src + n < dst) {
    \\ 同样需要判断是否可直接从前到后进行复制
		while (n--) {
			*tempDst = *src;
			tempDst++;
			src++;
		}
		*tempDst = '\0';
	}
	else {
		tempDst += n;
		*tempDst = '\0';
		tempDst--;
		src += n - 1;
		while (n--) {
			*tempDst = *src;
			tempDst--;
			src--;
		}
	}
	return dst;
}


int main() {
	cout << "memcpy example: " << endl;
	char src[] = "this is a test";
	char dst[10] = { 0 };
	myMemcpy(dst, src, 6);
	cout << dst << endl;

	cout << "memset example: " << endl;
	char str[9];
	int nums[9];
	myMemset(str, 0, sizeof(str));
	myMemset(nums, 0, sizeof(nums));

	for(int i = 0; i < 9; i++)
		cout << str[i] << ' ';
	cout << endl;

	for (int i = 0; i < 9; i++)
		cout << nums[i] << ' ';
	cout << endl;

	cout << "strcpy example: " << endl;
	char s1[20] = "";
	char s2[] = "Copy string";
	myStrcpy(s1, s2);
	cout << s1 << endl;

	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值