C语言内存函数

文章目录


一、memcpy使用和模拟实现

  • 函数memcpy从source的位置开始向后复制num个字节的数据到destination指向的内存位置。
  • 这个函数在遇到 '\0' 的时候并不会停下来。
  • 如果source和destination有任何的重叠,复制的结果都是未定义的。
1.1 使用
复制代码
#include<stdio.h>
#include <string.h>


int main()
{
	int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
	int arr2[10] = { 0 };
	memcpy(arr2, arr1, 20);
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		printf("%d ", arr2[i]);
	}
	return 0;
}
1.2 模拟实现
复制代码
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;
}

int main()
{
	int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
	int arr2[10] = { 0 };
	my_memcpy(arr2, arr1, 20);
	for (int i = 0; i < 10; i++)
		{
				printf("%d ", arr2[i]);
		}
			return 0;
}
  • 注意:void*的指针不能进行直接运算,所以要把它强转为 char* 类型的指针。
  • memcpy函数不负责重叠内存的拷贝,只负责不重叠的内存。

2、memmove使用和模拟实现

  • memmove和memcpy的差别就是memmove函数处理的源内存块和⽬标内存块是可以重叠的。
  • 如果源空间和⽬标空间出现重叠,就得使⽤memmove函数处理。
2.1 使用
复制代码
int main()
{
	int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
	memmove(arr1 + 2, arr1, 20);
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		printf("%d ", arr1[i]);
	}
	return 0;
}
2.2 模拟实现
复制代码
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;
}
  1. 区分当 dest > src 时,内存块从前往后拷贝:
  2. 当 dest > src 时,内存块从后往前拷贝:

三、memset函数的使用

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

    #include <stdio.h>
    #include <string.h>
    int main()
    {
    char str[] = "haoge c";
    memset(str, 'x', 5);
    printf(str);
    return 0;
    }

四、memcmp函数的使用

  • ⽐较从ptr1和ptr2指针指向的位置开始,向后的num个字节
  • 注意,与 strcmp 不一样,memcmp 当遇到 /0 后不会停止

返回值如下:

复制代码
#include <stdio.h>
#include <string.h>

int main()
{
	char buffer1[] = "hello bite";
	char buffer2[] = "hello world";

	int n;

	n = memcmp(buffer1, buffer2, sizeof(buffer1));

	if (n > 0) 
		printf("'%s' 大于 '%s'.\n", buffer1, buffer2);
	else if (n < 0) 
		printf("'%s' 小于 '%s'.\n", buffer1, buffer2);
	else 
		printf("'%s' 等于 '%s'.\n", buffer1, buffer2);

	return 0;
}

完结~~

相关推荐
景彡先生1 小时前
C++中的变量
c语言
2401_876907521 小时前
IEC 61347-1:2015 灯控制装置安全标准详解
大数据·数据结构·人工智能·算法·安全·学习方法
T.Ree.1 小时前
【数据结构】_排序
数据结构·算法·排序算法·排序
二进制的Liao1 小时前
【数据分析】什么是鲁棒性?
运维·论文阅读·算法·数学建模·性能优化·线性回归·负载均衡
这儿有一堆花3 小时前
比特币:固若金汤的数字堡垒与它的四道防线
算法·区块链·哈希算法
客卿1233 小时前
力扣100-移动0
算法·leetcode·职场和发展
CM莫问6 小时前
<论文>(微软)WINA:用于加速大语言模型推理的权重感知神经元激活
人工智能·算法·语言模型·自然语言处理·大模型·推理加速
计信金边罗8 小时前
是否存在路径(FIFOBB算法)
算法·蓝桥杯·图论
MZWeiei8 小时前
KMP 算法中 next 数组的构建函数 get_next
算法·kmp
Fanxt_Ja9 小时前
【JVM】三色标记法原理
java·开发语言·jvm·算法