C语言内存函数

文章目录

  • 前言
  • [1.memcpy 使用和模拟实现](#1.memcpy 使用和模拟实现)
  • [2.memmove 使用和模拟实现](#2.memmove 使用和模拟实现)
  • [3.memset 函数的使用](#3.memset 函数的使用)
  • [4.memcmp 函数的使用](#4.memcmp 函数的使用)

前言

通过前三篇的学习,我们学习了对字符以及字符串操作的函数,下面我们学习C语言内存函数


1.memcpy 使用和模拟实现

  • 函数memcpy从source的位置开始向后复制num个字节的数据到destination指向的内存位置。
  • 这个函数在遇到 '\0' 的时候并不会停下来。
  • 如果source和destination有任何的重叠,复制的结果都是未定义的。
c 复制代码
#include<stdio.h>
#include<string.h>
int main()
{
	int arr1[10] = { 1,2,3,4,5,6,7,8,9,10 };
	int arr2[20] = { 0 };
	memcpy(arr2, arr1, 20);//nums 字节
	for (int i = 0; i < 10; i++)
	{
		printf("%d ", arr2[i]);
	}
	return 0;
}

调试结果:

模拟实现

c 复制代码
void* my_memcpy(void* dest, const void* src, size_t num)
{
	void* ret = dest;
	assert(dest && src);
	while (num--)
	{
		*(char*)dest =*(char*)src;
		dest = (char*)dest + 1;
		src = (char*)src+ 1;
	}
	return ret;
}

2.memmove 使用和模拟实现

对于重叠的内存,交给memmove来处理。

c 复制代码
#include<stdio.h>
#include<string.h>
#include<assert.h>
int main()
{
	int arr1[10] = { 1,2,3,4,5,6,7,8,9,10 };
	memmove(arr1+3, arr1, 20);//nums 字节
	for (int i = 0; i < 10; i++)
	{
		printf("%d ", arr1[i]);
	}
	return 0;
}
  • 和memcpy的差别就是memmove函数处理的源内存块和目标内存块是可以重叠的。
  • 如果源空间和目标空间出现重叠,就得使用memmove函数处理。

模拟实现:

c 复制代码
void* my_memmove(void* dest, const void* src, size_t num)
{
	void* ret = dest;
	assert(dest && src);
	if(dest<src)
	{
		while (num--)
		{
			*(char*)dest = *(char*)src;
			dest = (char*)dest + 1;
			src = (char*)src + 1;
		}
	}
	else
	{
		while (num--)
		{
			*((char*)dest + num) = *((char*)src + num);
		}
	}
	return ret;
}

3.memset 函数的使用

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

c 复制代码
#include <stdio.h>
#include <string.h>
int main ()
{
 char str[] = "hello world";
 memset (str,'x',6);
 printf(str);
 return 0;
}

4.memcmp 函数的使用

c 复制代码
#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;
}

相关推荐
笑我归无处2 分钟前
强引用、软引用、弱引用、虚引用详解
java·开发语言·jvm
02苏_2 分钟前
秋招Java面
java·开发语言
ytttr87310 分钟前
64QAM信号的数字预失真处理(MATLAB实现)
开发语言·matlab
Nebula_g15 分钟前
C语言应用实例:硕鼠游戏,田忌赛马,搬桌子,活动选择(贪心算法)
c语言·开发语言·学习·算法·游戏·贪心算法·初学者
爱吃甜品的糯米团子23 分钟前
详解 JavaScript 内置对象与包装类型:方法、案例与实战
java·开发语言·javascript
QT 小鲜肉31 分钟前
【Git、GitHub、Gitee】按功能分类汇总Git常用命令详解(超详细)
c语言·网络·c++·git·qt·gitee·github
郝学胜-神的一滴44 分钟前
Linux下,获取子进程退出值和异常终止信号
linux·服务器·开发语言·c++·程序人生
AI科技星1 小时前
张祥前统一场论动量公式P=m(C-V)误解解答
开发语言·数据结构·人工智能·经验分享·python·线性代数·算法
CodeByV1 小时前
【C++】继承
开发语言·c++
权泽谦2 小时前
用 Python 做一个天气预报桌面小程序(附源码 + 打包与部署指导)
开发语言·python·小程序