C++
const char *C_STR (); the C_STR () function returns a pointer constant to the normal C string with the same contents as this string string. (In fact, it points to a real char buffer inside a string object), so returns a const to prevent the user from modifying it. This is to be compatible with the C language, there is no string type in C, so the string object must be converted to a string style in C by using the member function C_str () of the String class object.
when you manipulate the return value of the C_STR () function, you can use only the function of the C string, such as strcpy (). Because a string object may be freed by a destructor after it is used, the content you point to is nondeterministic.
{
string var = "Olympic";
Char *ptr = VAR.C_STR ();
}//cannot be compiled, because VA.C_STR () returns a temporary pointer, assigned to PTR, and after the end of the}, the Var object is refactored, and the final use of PTR, which is garbage content
A, C-language string
In the C language, the processing of strings is a painful thing, because usually in the implementation of the operation of the string will be the most difficult type-pointer.
For example, the following:
Example 1:
Char str[12] = "Hello";
char *p = str;
*p = ' h '; Change the first letter
Example 2:
Char *ptr = "Hello";
*ptr = ' h '; Error
The first string is opened with an array, and it is a variable that can be changed. The second string is a constant, which is the literal value. PTR is just a pointer to it, and cannot change what it points to.
To change a constant through a pointer is an error, the correct wording should be a const pointer.
const char *ptr = "Hello";
Second, the first knowledge of the String class
It is because C-style strings (character arrays that end in a null character) that are too complex to master and not suitable for large program development, so the C + + standard library defines a string class defined in header file <string>. Note <string.h> and <cstring> are all wrong, these two header files mainly define some methods of C-style string manipulation, such as strlen (), strcpy (), etc. The first is the header file format for C, and the second is a C + + style header file, but it is the same as <string.h>, and it is designed to be compatible with C.
Look at the following example:
Example 3:
String str ("World"); Can be initialized with a C-style string
String words = "Hello";
string greet = words;
String join = greet + words; Can operate like a basic type
C + + STRING.C_STR () Summary