Home c++ How does c_str () work in C++?

How does c_str () work in C++?




I’m interested in how the array to which the pointer looks like.

As I understand it, the function takes a string for example string str = “12345” and turns it into an array of charms {‘1’, ‘2’, ‘3’, ‘4’, ‘5’, \ 0} and then returns a pointer to this array

Or so {“12345”}?

And another such moment, if it returns a pointer, then why does this work:

cout << str.c_str() <<endl; 

Answer 1, authority 100%

As I understand it, string::c_strreturns a pointer to the area of ​​memory where it stores the string itself. That is, when returning, it does not create any additional arrays, nothing converts or copies anywhere.

About cout << str.c_str() <<endl;: coutprints pointers like char *or const char *fine like strings. You won’t be confused by the cout << "12345" << endl;

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions