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 name space std;
void Test( void ) { 
char *str1=NULL; 
str1=newchar[ 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