zoukankan      html  css  js  c++  java
  • strcpy_s与strcpy的比较

    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

  • 相关阅读:
    如何限制ip访问Oracle数据库
    11G oracle RAC集群启动和关闭
    查看Oracle某时刻的客户端IP连接情况
    ASM--文件系统之间归档日志的拷贝
    Oracle AWR内容详解
    Oracle RMAN操作详解
    静默升级oracle 11g (从11.2.0.1升级到11.2.0.4)
    XStream使用详解
    Go 测试单个方法
    Golang 单元测试和性能测试
  • 原文地址:https://www.cnblogs.com/lancidie/p/2986070.html
Copyright © 2011-2022 走看看