The functions of strcpy_s and strcpy () functions are almost the same. The strcpy function, just like the gets function, has no way to ensure a valid buffer size, so it can only assume that the buffer is large enough to accommodate the string to be copied. During program execution, this will lead to unpredictable behavior. Use strcpy_s These unpredictable behaviors can be avoided.
This function can use both the number of buffers and the number of three buffers to ensure the buffer size.
When there are three shards:
Errno_t strcpy_s (
Char * strdestination,
Size_t numberofelements,
Const char * strsource
);
When there are two shards:
Errno_t strcpy_s (
Char (& strdestination) [size],
Const char * strsource
); // C ++ only
Example:
# 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 shards Strcpy_s (STR, "hello ");//The number of two partitions is assumed to be char * STR = new char [7]. An error occurs: The system prompts that two partitions are not supported. 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"); // it is assumed that char * STR = new char [7]; an error occurs: the message "cout <" strlen (str1): "<strlen (str1) <Endl <" strlen (STR): "<strlen (STR) <Endl; printf (str1); printf ("\ n"); cout <STR <Endl ;}
Int main () {test (); Return 0 ;}
Output:
Strlen (str1): 11// Note that strlen (str1) is used to calculate the length of a string and does not contain "\ 0" at the end of the string "!!!
Strlen (STR): 5
Hello World
Hello