C++安全函数之strcpy_s

C++安全函数之strcpy_s
1.  必须包含的头文件:<string.h>
2.  函数声明:
errno_t strcat_s(  
   char *strDestination,  
   size_t numberOfElements,  
   const char *strSource   
); 
3.  参数介绍
  strDestination
  目标字符串缓冲区的位置。
  numberOfElements
  多字节窄函数 char 单元以及宽函数 wchar_t 单元中的目标字符串缓冲区的大小。
  strSource
  以 null 结尾的源字符串缓冲区。

4.  使用例子
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

int main( void )
{
	char string[80];
	// using template versions of strcpy_s and strcat_s:
	strcpy_s( string, "Hello world from " );
	strcat_s( string, "strcpy_s " );
	strcat_s( string, "and " );
	// of course we can supply the size explicitly if we want to:
	strcat_s( string, _countof(string), "strcat_s!" );

	printf( "String = %s\n", string );
	system("Pause");
}
5.  注意事项 在使用strcpy_s,使用两个参数的时候要特别注意的一点是,两个参数但如果:char *str=new char[7];会出错:提示不支持两个参数。new出来的字符串,提示不支持两个参数,所以必须用三个参数的。
#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;
        cout << str1 << endl;
	cout << str << endl;
}

int main()
{
	Test();
	system("Pause");
	return 0;
}
输出为:
strlen(str1): 11        //另外要注意:strlen(str1)是计算字符串的长度,不包括字符串末尾的“\0”!!!
strlen(str): 5
hello world
hello

  • 7
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值