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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM