C++ memcpy()

C++ 中的 memcpy() 函数将指定字节的数据从源复制到目标。它定义在 cstring 头文件中。

示例

#include <cstring>
#include <iostream>
using namespace std;

int main() {
  char source[] = "Tutorial";
  char destination[] = "Programiz";

// copy all bytes of source to destination memcpy(destination, source, sizeof(source));
cout << destination; return 0; } // Output: Tutorial

memcpy() 语法

memcpy() 函数的语法是

memcpy(void* dest, const void* src, size_t count);

memcpy() 参数

memcpy() 函数接受以下参数

  • dest - 要将内容复制到的内存位置的指针。它属于 void* 类型。
  • src - 要将内容复制自的内存位置的指针。它属于 void* 类型。
  • count - 从 src 复制到 dest 的字节数。它属于 size_t 类型。

注意:由于 srcdest 的类型是 void*,因此我们可以将大多数数据类型与 memcpy() 一起使用。


memcpy() 返回值

memcpy() 函数返回

  • dest - 目标的内存位置

memcpy() 原型

在 cstring 头文件中定义的 memcpy() 的原型是

void* memcpy(void* dest, const void* src,size_t count);

当我们调用此函数时,它会将 src 指向的内存位置的 count 字节复制到 dest 指向的内存位置。


memcpy() 未定义行为

如果以下任一条件成立,则 memcpy() 的行为是未定义的:

  • srcdest 是空指针,或者
  • 对象重叠。

示例 1:C++ memcpy()

#include <cstring>
#include <iostream>
using namespace std;

int main() {
  char source[] = "Tutorial";
  char destination[] = "Programiz";

  cout << "Initial destination: " << destination << endl;

// copy all bytes of destination to source memcpy(destination, source, sizeof(source));
cout << "Final destination: " << destination; return 0; }

输出

Initial destination: Programiz
Final destination: Tutorial

在这里,我们使用 sizeof() 函数将 source 的所有字节复制到了 destination


示例 2:C++ memcpy() - 仅复制 source 的一部分

#include <cstring>
#include <iostream>
using namespace std;

int main() {
  char source[] = "Tutorial";
  char destination[] = "Programiz";

  cout << "Initial destination: " << destination << endl;

// copy 4 bytes of destination to source memcpy(destination, source, 4);
cout << "Final destination: " << destination; return 0; }

输出

Initial destination: Programiz
Final destination: Tutoramiz

在这里,我们只将 source 的 4 个字节复制到了 destination

由于一个 char 数据占用 1 个字节,因此此程序会将 destination 的前 4 个字符替换为 source 的前 4 个字符。


示例 3:C++ memcpy() 与整数类型

#include <cstring>
#include <iostream>
using namespace std;

int main() {
  int source[10] = {8,3,11,61,-22,7,-6,2,13,47};
  int destination[5];

// copy 5 elements (20 bytes) of source to destination memcpy(destination, source, sizeof(int) * 5);
cout << "After copying" << endl; for (int i=0; i<5; i++) cout << destination[i] << endl; return 0; }

输出

After copying
8
3
11
61
-22

在这里,我们创建了两个大小分别为 105int 数组 source[]destination[]

然后,我们使用 memcpy() 函数将 source[] 的 5 个元素复制到 destination[]

memcpy(destination, source, sizeof(int) * 5);

请注意参数 sizeof(int) * 5sizeof(int) 代码给出单个 int 数据占用的总字节数,即 4 个字节。

由于我们要将 source[] 的 5 个 int 元素复制到 destination[],因此我们将 sizeof(int) 乘以 5,这等于 20 字节的数据。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战