std::strcpy、strncpy、memset、memcpy用法

这篇博客详细介绍了C++和C语言中四个常用的字符串及内存操作函数:std::strcpy用于完整复制字符串,std::strncpy则可以指定复制部分字符,std::memcpy用于缓冲区之间的复制,而std::memset用于填充内存块。每个函数的使用方法、参数说明和示例代码都有清晰的解释。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. std::strcpy

功能:将一个字符串复制到另一个字符串(如果字符串重叠,该行为是未定义);
定义于头文件 <cstring>

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

参数:
destination

Pointer to the destination array where the content is to be copied.

source

C string to be copied.

Return Value

destination is returned.

dest :指向复制内容存放的首地址
src :需要被复制的C风格的字符串
返回值 :复制后的字符串的首地址

Example:

/* strcpy example */
#include <iostream>
 #include <cstring>
 using namespace std;
  int main ()
  {
    char str1[]= "Sample string";
    char str2[40];
    char str3[40];
   strcpy (str2,str1);
   strcpy (str3,"copy successful");

   cout<<"str1:"<<str1<<endl;
   cout<<"str2:"<<str2<<endl;
   cout<<"str3:"<<str3<<endl;

   return 0;
 }

Output:

str1: Sample string
str2: Sample string
str3: copy successful

2.std::strncpy

定义于头文件<cstring>

char *strncpy( char *dest, const char *src, std::size_t count );

功能:将一个字符串的一部分复制到另一个字符串;
说明:从原地址source开始,复制num个字符到dest开始的地址;
destination

Pointer to the destination array where the content is to be copied.

source

C string to be copied.

num
Maximum number of characters to be copied from source.
size_t is an unsigned integral type.

说明:从源地址source开始,复制num个字符到dest开始的地址

Example

C版:

    /* strncpy example */
#include &
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值