博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
strcpy_s与strcpy的比較
阅读量:7238 次
发布时间:2019-06-29

本文共 1245 字,大约阅读时间需要 4 分钟。

 
strcpy_s和strcpy()函数的功能差点儿是一样的。
strcpy函数,就象gets函数一样,它没有方法来保证有效的缓冲区尺寸,所以它仅仅能假定缓冲足够大来容纳要拷贝的字符串。在程序执行时,这将导致不可预料的行为。
用strcpy_s就
能够避免这些不可预料的行为。
这个函数用两个參数、三个參数都能够,仅仅要能够保证缓冲区大小。
三个參数时:
errno_t strcpy_s(
char *strDestination,
size_t numberOfElements,
const char *strSource
);
两个參数时:
errno_t strcpy_s(
char (&strDestination)[size],
const char *strSource
); // C++ only
样例:
#include<iostream>
#include<cstring>
using namespace std;
void Test(void)
{
char *str1=NULL;
str1=new char[20];
char str[7];
strcpy_s(str1,20,"hello world");//三个參数
strcpy_s(str,"hello");//两个參数但假设:char *str=new char[7];会出错:提示不支持两个參数
cout<<"strlen(str1):"<<strlen(str1)<<endl<<"strlen(str):"<<strlen(str)<<endl;
printf(str1);
printf("\n");
cout<<str<<endl;
}
int main()
{
Test();
return 0;
}
#include<iostream>
#include<string.h>
using namespace std;
void Test(void)
{
char *str1=NULL;
str1=new char[20];
char str[7];
strcpy_s(str1,20,"hello world");//三个參数
strcpy_s(str,"hello");//两个參数但假设:char *str=new char[7];会出错:提示不支持两个參数
cout<<"strlen(str1):"<<strlen(str1)<<endl<<"strlen(str):"<<strlen(str)<<endl;
printf(str1);
printf("\n");
cout<<str<<endl;
}
int main()
{
Test();
return 0;
}
输出为:
strlen(str1): 11        //另外要注意:strlen(str1)是计算字符串的长度,不包含字符串末尾的“\0”!!!
strlen(str): 5
hello world
hello

转载地址:http://xprfm.baihongyu.com/

你可能感兴趣的文章
C#连接数据库
查看>>
重定向和管道的区别
查看>>
分层、链式分析、url、联系的长度
查看>>
C++实现ping功能<转>
查看>>
使用matplotlib绘制收入增长模型——线性积累型与指数复利型
查看>>
【Spark】Spark-Redis连接池
查看>>
网络流简介
查看>>
How to fix “HTTP Status Code 505 – HTTP Version Not Supported” error?--转
查看>>
mybatis结合mysql批量操作及查询sql
查看>>
groovy gradle 构建配置
查看>>
Linux时间子系统(十五) clocksource
查看>>
BaseRecyclerViewAdapterHelper使用
查看>>
请说出三种减少页面加载时间的方法。
查看>>
HDU 2036 改革春风吹满地
查看>>
Deepin-快捷方式设置
查看>>
管理Java垃圾回收的五个建议
查看>>
【MySQL】MySQL的索引
查看>>
数数字
查看>>
配置阿里云Docker镜像加速仓库
查看>>
社交的基本逻辑
查看>>