Strlen () and strcpy () functions, strlenstrcpy Functions
The difference between strlen () and strcpy () functions. One is to return the length of a C-style string, and the other is to copy a C-style string, the two functions are different. In addition, they have some minor differences: The result returned by strlen ("hello") is 5, which isDoes not contain'\ 0', But strcpy (str1, str2 ),Copy'\ 0'.
When using the return value of strlen () to allocate space for the first parameter of strcpy, be sure to pay attention!
For example:
Char * str = "hello ";
Int length = strlen (str );
Char char_array [5];
Strcpy (char_array, str );
Printf ("the new string is: % s \ n", char_array );
Cout <"str's length is:" <length <endl;
In this way, the output length is 5, but the compiler will prompt an error. The VS2010 prompt is:
This indicates that the definition of the string array is small. If the definition is changed to an array of 6, the system returns to normal.
When using strcpy, we recommend that you set the size of the target array (the first parameter) to the value of strlen () function return value + 1, or use the following initialization array method:
Char char_array [sizeof ("hello")];
Char * char_array_two = new char [strlen (str) + 1];