c语言内存函数模拟及实现

⽬录:
1. memcpy使⽤和模拟实现
2. memmove使⽤和模拟实现
3. memset函数的使⽤
4. memcmp函数的使⽤

一. memcpy使⽤和模拟实现:

1.函数memcpy从source的位置开始向后复制num个字节的数据到destination指向的内存位置。

2.如果source和destination有任何的重叠,复制的结果都是未定义的。并且遇到'\0'是不会停下来的

 

代码如下: 

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
void* my_memcpy(void* dest, const void* src, size_t num)
{
	assert(dest && src);
	void* ret = dest;
	while (num--)
	{
		*(char*)dest = *(char*)src;
		dest = (char*)dest +  1;
		src = (char*)src + 1;
	}
	return ret;
}
int main()
{
	int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
	int arr1[20] = { 0 };
	my_memcpy(arr1, arr, 20);//这里的20单位是字节
	for (int i = 0;i < 10; i++)
	{
		printf("%d ", arr1[i]);
	}
	return 0;
}

二.memmove函数使⽤和模拟实现 

1.和memcpy的差别就是memmove函数处理的源内存块和⽬标内存块是可以重叠的


 

代码如下:

#include <stdio.h>
#include <string.h>
#include <assert.h>
//使用:
//int main()
//{
//	int arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//	memmove(arr + 3, arr, 4 * sizeof(int));
//	for (int i = 0; i < 11; i++)
//	{
//		printf("%d ", arr[i]);
//
//	}
//	return 0;
//}

//memmove模拟:
void* my_memmove(void* dest, const void* src, size_t num)
{

	assert(dest && src);
	void* ret = dest;
	//后->前
	if (dest > src)
	{
		while (num--)//num先使用后--,num第一次循环 = 16字节
		{
			(*((char*)dest + num)) = (*((char*)src + num));//num第一次循环 = 15字节
		}
	}
	//前->后
	else
	{
		while (num--)
		{
			(char*)dest = (char*)src;
			dest = (char*)dest + 1;
			src = (char*)src + 1;
		}
	}

}
int main()
{
	int arr[11] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	my_memmove(arr+3, arr, 4 * sizeof(int));
	for (int i = 0; i < 11; i++)
	{
		printf("%d ", arr[i]);
	}
	return 0;
}

 

 这个我画了个图可以辅助理解这段代码:我们知道数组在内存中的储存是从低地址到高地址,如图所示。如果dest > src,把src从后往前给dest,如果dest < src则反之。

 

三. memset函数的使⽤ 

1.memset是⽤来设置内存的,将内存中的值以字节为单位设置成想要的内容

 

代码:

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
int main()
{
	int arr[5] = { 0 };
	memset(arr, 1, 20);//该函数以字节为单位操作内存
	for (int i = 0; i < 4; i++)
	{
		printf("%d ", arr[i]);

	}

	return 0;
}

四. memcmp函数的使⽤ 

#include <stdio.h>
#include <string.h>

int main()
{
	char buffer1[] = "DWgaOtP12df0";
	char buffer2[] = "DWGAOTP12DF0";
	int n;
	n = memcmp(buffer1, buffer2, sizeof(buffer1));

	if (n > 0) 
		printf("'%s' is greater than '%s'.\n", buffer1, buffer2);
	else if (n < 0)
		printf("'%s' is less than '%s'.\n", buffer1, buffer2);
	else 
		printf("'%s' is the same as '%s'.\n", buffer1, buffer2);
	return 0;
}

 

 

 

 


 

 

 

 

 

 

 


 


 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

robin_suli

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值