C语言内存函数memcpy与memmove

一.memcpy的使用和模拟实现

1.函数原型

复制代码
void* memcpy(void* destination, const void* source, size_t num);

destination是目标内存块的指针

source是源内存块的指针

num是要复制的字节数
.函数memcpy从source的位置开始向后复制 num个字节 的数据到destination指向的内存位置。
.这个函数在遇到 '\0' 的时候并不会停下来。
.如果source和destination有任何的重叠,复制的结果都是未定义的。

PS:memcpy函数只关心内存块的二进制表示,不关心其所代表的数据类型,因此可能会出现类型转换问题。此外,在使用memcpy函数时需要确保目标内存块有足够的空间来存储源内存块中的数据,否则会导致内存越界错误。

2.代码使用

复制代码
#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);
     //注意是20个字节
     int i = 0;
     for (i = 0; i < 10; i++)
     {
         printf("%d ", arr2[i]);
     }
     return 0;
}

3.memcpy的模拟实现

复制代码
#include<stdio.h>
void *my_memcpy(void *p1,const void *p2,int n)
{
	int i=0;
	for(i=0;i<n;i++){
		*(char*)p1=*(char*)p2;
		p1++;
		p2++;
	}
}
int main()
{
	int arr1[20]={1,2,3,4,5,6,7,8,9,10};
	int arr2[5]={1,2,3,4,5};
	my_memcpy(arr1+3,arr2,5*sizeof(int));
	int i=0;
	for(;i<20;i++){
		printf("%d ",arr1[i]);
	}
	
	return 0;
}

二.memmove的使用与模拟实现

1.函数原型

复制代码
void * memmove ( void * destination, const void * source, size_t num );

memmove函数会将src指针指向的内存区域中的前num个字节复制到dest指针指向的内存区域中。

PS:与memcpy函数相比,memmove函数更加灵活,因为它能够处理源地址与目的地址重叠的情况。但是,由于memmove函数需要进行更多的判断和处理,所以在一些情况下,memcpy函数可能更加高效。

2.代码使用

复制代码
#include <stdio.h>
#include <string.h>
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 ", arr2[i]);
  }

  return 0;
}

3.memmove的代码模拟实现

复制代码
#include<stdio.h>
void *my_memmove(void *p1,const void *p2,int n)
{
	int i=0;
	if(p1<p2){
		for(i=0;i<n;i++){
			*(char*)p1=*(char*)p2;
			p1++;
			p2++;
		}
	}
	else
	{
		while(n--)
			*((char*)p1+n)=*((char*)p2+n);
	}
}
int main()
{
	int arr[10]={1,2,3,4,5,6,7,8,9,10};
	my_memmove(arr+2,arr,4*sizeof(int));
	int i=0;
	for(;i<10;i++){
		printf("%d ",arr[i]);
	}
	
	return 0;
}

相关推荐
RuoZoe6 天前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
祈安_9 天前
C语言内存函数
c语言·后端
郑州光合科技余经理11 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo12311 天前
matlab画图工具
开发语言·matlab
dustcell.11 天前
haproxy七层代理
java·开发语言·前端
norlan_jame11 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone11 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ40220549611 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
czy878747511 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
遥遥江上月11 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js