strcpy_s函数两个参数和三个参数

29 篇文章 0 订阅
         看名字明白,它和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 "stdafx.h"
#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)<<"strlen(str)"<<strlen(str)<<endl;
printf(str1);printf("\n");
cout<<str<<endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
    Test();
    return 0;
}

输出为:
strlen(str1): 11
strlen(str): 5
hello world
hello

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值