the strcpy_s and strcpy () functions are almost identical. The strcpy function. Just like the Get function, it has no way to guarantee a valid buffer size, so it can only assume that the buffer is large enough to hold the string to be copied. This leads to unpredictable behavior when the program is executed.
with strcpy_s, To avoid these unpredictable behaviors.
This function can be used with two parameters and three parameters, only to guarantee the buffer size.
Three parameters:
errno_t strcpy_s (
Char *strdestination,
size_t numberofelements,
const char *strsource
);
two parameters:
errno_t strcpy_s (
char (&strdestination) [size],
const char *strsource
); C + + only
Examples:
#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");//Three referencesstrcpy_s (str, "Hello");// two references but assumes: Char *str=new char[7]; Error: Prompt does not support two parameters 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");//three Parameters strcpy_s (str, " Hello ");//Two references but assumes: Char *str=new char[7]; Error: Prompt does not support two parameters cout<<" strlen (str1): "<<strlen (STR1) <<endl << "strlen (str):" <<strlen (str) <<endl;printf (STR1);p rintf ("\ n"); Cout<<str<<endl;}
int main () {Test (); return 0;}
the output is:
strlen ( str1): one///Another note: strlen (str1) is the length of the computed string. does not contain "\" at the end of the string!!!
strlen (str): 5
Hello World
Hello
Comparison of strcpy_s and strcpy