strcpy_s与strcpy对照
生活随笔
收集整理的這篇文章主要介紹了
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
這個函數用兩個參數、三個參數都能夠,僅僅要能夠保證緩沖區大小。
三個參數時:
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
轉載于:https://www.cnblogs.com/mengfanrong/p/4580442.html
總結
以上是生活随笔為你收集整理的strcpy_s与strcpy对照的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VSTO之旅系列(三):自定义Excel
- 下一篇: 6.2 基本操作与存储