C++ strcpy()

C++ 中的 strcpy() 函数将一个字符 字符串 从源复制到目标。它定义在 cstring 头文件中。

示例

#include <cstring>
#include <iostream>

using namespace std;

int main() {
  char src[] = "Hello Programmers.";
    
  // large enough to store content of src
  char dest[20];

// copy the contents of src to dest strcpy(dest,src);
cout << dest; return 0; } // Output: Hello Programmers.

strcpy() 语法

strcpy() 的语法是

strcpy( char* dest, const char* src );

strcpy() 参数

strcpy() 函数接受以下参数

  • dest - 指向 C 字符串的 指针,内容将被复制到其中
  • src - 指向 C 字符串的指针,内容将从此复制

strcpy() 返回值

strcpy() 函数返回

  • dest (指向目标 C 字符串的指针)

strcpy() 原型

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

char* strcpy(char* dest, const char* src);

strcpy() 函数将 src 指向的 C 字符串复制到 dest 指向的内存位置。空终止字符 '\0' 也会被复制。

请注意

  • srcconst char* 类型。const 关键字确保 src 指向的 C 字符串不能被 strcpy() 修改。
  • destchar* 类型。没有 const 确保 dest 指向的 C 字符串可以被 strcpy() 修改。

strcpy() 未定义行为

如果以下情况发生,strcpy() 的行为是未定义的

  • dest 指针分配的内存不够大。
  • 字符串重叠。

示例:C++ strcpy()

#include <cstring>
#include <iostream>

using namespace std;

int main() {
  char src[20] = "I am the source.";

  // large enough to store content of src
  char dest[30] = "I am the destination.";
    
  cout << "dest[] before copy: " << dest << endl;

// copy contents of src to dest strcpy(dest,src);
cout << "dest[] after copy: " << dest; return 0; }

输出

dest[] before copy: I am the destination.
dest[] after copy: I am the source.

另请阅读

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

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

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

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