strcpy_s与strcpy的比較
strcpy
2023-09-14 09:08:12 时间
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
样例:
输出为:
strlen(str1): 11 //另外要注意:strlen(str1)是计算字符串的长度,不包含字符串末尾的“\0”!!!
strlen(str): 5
hello world
hello
这个函数用两个參数、三个參数都能够,仅仅要能够保证缓冲区大小。
三个參数时:
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;
}
输出为:
strlen(str1): 11 //另外要注意:strlen(str1)是计算字符串的长度,不包含字符串末尾的“\0”!!!
strlen(str): 5
hello world
hello
相关文章
- strncpy和strcpy区别_C语言strncpy
- 【如何手写strcpy和memcpy】c++面试常问问题总结01
- c++-strcpy函数的实现
- C语言strcpy(),memcpy(),memmove() | 数组赋值给数组
- 【C 语言】C 字符串 ( 表示方法 | strcpy | strcat | strlen | strcmp )
- Using strcpy to Manipulate Linux Files(strcpylinux)
- C++ strcpy:字符串赋值函数
- C语言strcpy()函数:字符串复制(拷贝)函数
- Linux strcpy:快速、安全的字符串复制(linuxstrcpy)
- 内核 深入浅出Linux内核之strcpy(strcpylinux)
- C语言-字符串函数的实现(二)之strcpy
- 自己实现strcpy函数的实现方法
- 深入分析C中不安全的sprintf与strcpy
- 深入理解strcpy与memcpy的区别
- 用C++实现strcpy(),返回一个char*类型的深入分析
- C语言中字符串常用函数strcat与strcpy的用法介绍
- 浅析C++中memset,memcpy,strcpy的区别
- strcpy函数实现简示例命分享