30 - memcpy()函数

1 函数原型

memcpy():拷贝内存块,函数原型如下:

void * memcpy ( void * destination, const void * source, size_t num );

cstring库描述如下:

Copy block of memory
1. Copies the values of num bytes from the location pointed to by source directly to the memory block pointed to by destination.
2. The underlying type of the objects pointed to by both the source and destination pointers are irrelevant for this function; The result is a binary copy of the data.
3. The function does not check for any terminating null character in source - it always copies exactly num bytes.
4. To avoid overflows, the size of the arrays pointed to by both the destination and source parameters, shall be at least num bytes, and should not overlap (for overlapping memory blocks, memmove is a safer approach).
  1. memcpy()函数:
    (1)从source指向的内存块直接复制num个字节的值到destination指向的内存块;
    (2)复制过程按字节进行,与源内存块source和目标内存块destination中存储的数据类型无关;
  2. 注意事项
    (1)内存块足够大:必须确保源内存块source和目标内存块destination都有足够的空间来存储num个字节的数据;
    (2)内存不能重叠:源内存块source和目标内存块destination不能够重叠。

2 参数

memcpy()函数有三个参数source、destination和num:

  1. source是指向源内存块的指针,类型为void*;
  2. destination是指向目标内存块的指针,类型为void*;
  3. num是要复制的字符数,类型为size_t。

cstring库描述如下:

destination
1. Pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*.

source
1.Pointer to the source of data to be copied, type-casted to a pointer of type const void*.

num
1. Number of bytes to copy.
2. size_t is an unsigned integral type.

3 返回值

memcpy()函数的返回值类型为void*型:

  1. 返回指向目标内存块的指针destination。

cstring库描述如下:

1. destination is returned.

4 示例

4.1 示例1

示例代码如下所示:

int main() {
   //
   char src[] = "Hello, World!";
   char dest[20] = { 0 };
   //
   memcpy(dest, src, strlen(src) + 1);
   //
   printf("源字符串:\t%s\n", src);
   printf("目标字符串:\t%s\n", dest);
   //
   return 0;
}

代码运行结果如下图所示:

在这里插入图片描述

4.2 示例2

VS2019对memcpy()函数进行了优化,已无法模拟内存重叠的情况;编写自己的内存拷贝函数,示例代码如下所示:

void* my_memcpy(void* dest, const void* src, size_t n) {
   //
   assert(src != NULL);
   assert(dest != NULL);
   //
   char* d = (char*)dest;
   const char* s = (const char*)src;
   // 
   for (size_t i = 0; i < n; i++) {
      d[i] = s[i];
   }
   //
   return dest;
}

int main() {
   //
   char str[] = "abcdefghijklmn";
   //
   printf("复制前:%s\n", str);
   //
   my_memcpy(str + 6, str + 4, 6);
   //
   printf("复制后:%s\n", str);
   //
   return 0;
}

代码运行结果如下图所示:

在这里插入图片描述

代码及运行结果分析如下:

  1. 期望用"efghij"替换"ghijkl",结果是"efefef"替换"ghijkl"。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值