STRING.C_STR () Usage and Precautions and string::copy () and String.data ()

Source: Internet
Author: User

Turn from: http://zhidao.baidu.com/question/104592558.html

http://blog.csdn.net/xiaoniba10631/article/details/6705214

Prototype: const char *C_STR ();
The C_STR () function returns a pointer to the normal C string, which is the same as the string string.
This is to be compatible with the C language, and there is no string type in C, so you must convert the string object to a string style in C by C_str () the member function of the String class object.


Note: Be sure to use the strcpy () function to manipulate methods C_STR () the pointer returned
For example: It's best not to:
const char* C;
String s= "1234";
c = S.c_str ();

Because: it is very dangerous to do so:

Example code:

const char* C;
String s= "1234";
c = S.c_str ();
S.append ("ABCD");
printf ("%s\n", c);
cout << c << Endl;

The output results are:

1234abcd
1234abcd

Analysis: Pointer c will directly point to S, operating the same piece of memory, and will not be new to open the interior from space, which is undoubtedly dangerous.


This should be done in this way:
Char c[20];
String s= "1234";
strcpy (C,s.c_str ());

Let me give you an example.
C_STR () returns a string containing string in char* form
If a function requires char* parameters, you can use the C_str () method:
string s = "Hello world!";
printf ("%s", S.c_str ()); Output "Hello world!"

String.data (): Similar to C_str (), but the returned array does not terminate with a null character.

String::copy () For example:

Char c2[11] = {0};
String s2 = "";
S2 = "Hello boy!";
int irtn = s2.copy (c2, 10, 0);/function will be S2, starting from the No. 0, a total of 10 characters copied to the C2, Irtn for the number of copied characters, here 10.

Note: Irtn Returns the number of bytes actually copied, and when the second argument is longer than the string itself, the length of the string is returned.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.