memcpy与memmove详解:

memcpy与memmove详解:


在这里插入图片描述

将num字节的值从源指向的位置直接复制到目标指向的内存块。

源指针和目标指针所指向的对象的底层类型与此函数无关;结果是数据的二进制副本。

该函数不检查源文件中的任何终止空字符——它总是准确地复制num字节。

为了避免溢出,目标和源参数所指向的数组的大小应该至少为num字节,并且不应该重叠(对于重叠的内存块,memmove是一种更安全的方法

memcpy模拟实现:
#include<stdio.h>
#include<string.h>
#include<assert.h>

void* my_memcpy(void* dest, const void* src, size_t count)
{
	void* ret = dest;
	assert(dest != NULL);
	assert(src != NULL);
	while (count--)
	{
		*(char*)dest = *(char*)src;
		++(char*)dest;
		++(char*)src;

	}
	return ret;
}

int main()
{
	char arr1[] = "abc";
	char arr2[] = "def";
	void* ret = my_memcpy(arr1, arr2, 1);
	printf("%s", arr1);
	return 0;

}

举例:
/* memcpy example */
#include <stdio.h>
#include <string.h>

struct {
  char name[40];
  int age;
} person, person_copy;

int main ()
{
  char myname[] = "Pierre de Fermat";

  /* using memcpy to copy string: */
  memcpy ( person.name, myname, strlen(myname)+1 );
  person.age = 46;

  /* using memcpy to copy structure: */
  memcpy ( &person_copy, &person, sizeof(person) );

  printf ("person_copy: %s, %d \n", person_copy.name, person_copy.age );

  return 0;
}

在这里插入图片描述

memmove:

在这里插入图片描述
将num字节的值从源指向的位置复制到目标指向的内存块。复制发生时,就像使用了中间缓冲区一样,允许目标和源重叠。

源指针和目标指针所指向的对象的底层类型与此函数无关;结果是数据的二进制副本。

该函数不检查源文件中的任何终止空字符——它总是准确地复制num字节。

为了避免溢出,目标参数和源参数所指向的数组的大小应该至少为num字节。

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

void* my_memmove(void* destination, void* source, size_t num)
{
	void* result = destination;
	while (num--)
	{
		if (source > destination)
		{
			*(char*)destination = *(char*)source;
			source = (char*)source + 1;
			destination = (char*)destination + 1;
		}
		else
		{
			*((char*)destination + num) = *((char*)source + num);
		}
	}
	return result;
}
int main()
{
	int a[] = { 1,2,3,4,5,6,7,8,9,10 };
	my_memmove(a + 4, a + 2, 20);
	for (int i = 0; i < 10; i++)
	{
		printf("%d ", a[i]);
	}
	return 0;
}

举例:
/* memmove example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] = "memmove can be very useful......";
  memmove (str+20,str+15,11);
  puts (str);
  return 0;
}

#include <string.h>

int main ()
{
char str[] = “memmove can be very useful…”;
memmove (str+20,str+15,11);
puts (str);
return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值