Click here to Skip to main content
15,904,024 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,
My code snippet looks like this:
int main() {
        string s1("One\n");
	const char* s2 = s1.c_str();
	cout << s2 << s1;
	s2 = "Two\n";
	cout << s2 << s1;
}

Output:
One
One
Two
One

My doubts are:
-> Can we modify the const char* like shown above after initialization?!
-> Does the c_str() function return actual base address of string's character array?If yes then why is the s1 value not changed?

Thanks in advance
Posted

HarishTheLearner wrote:
-> Can we modify the const char* like shown above after initialization?!

Yes, (like Obama) we can.

HarishTheLearner wrote:
does the c_str() function return actual base address of string's character array?If yes then why is the s1 value not changed?

Again, yes (see basic_string::c_str[^] documentation).


A little explanation:

C++
const char* s2 = s1.c_str();

Declares s2 as a pointer (a variable containing an address) to a (const) sequence of characters.
The same statement initializes it to point at s1 character sequence.

C++
s2 = "Two\n";

This change to s2 value modifies just the pointed address: now s2 points to the character sequence (the literal string) "Two\n", so that it points no more to s1 character sequence.

Now the output should be obvious.

BTW: never try to change the std::string content using the address provided by c_str() method.

:-)
 
Share this answer
 
Comments
Stefan_Lang 26-May-11 8:22am    
perfect, 5!

You might want to add that the right way to assign a new value to s1 is simply s1="Two"; (or whatever) ;-)
hakz.code 26-May-11 8:23am    
Hi Pallini,
just to be clear - When I do *(s2+1) = 'M'; it gives the error that you cannot modify const var,but how does s2 = "LiteralConst" work?
CPallini 26-May-11 8:29am    
because *(s2+1)='M' is trying to modify the content of a constant memory buffer. On the other hand, s2 = "FOO" just changes the pointer value (makes s2 pointing to another memory area).
hakz.code 26-May-11 8:31am    
Thanks!that gives me clear idea..
CPallini 26-May-11 8:38am    
You are welcome.
yes we can modify.

try the following code, but it is not safe.

MIDL
int _tmain(int argc, _TCHAR* argv[])
{
    std::string strName = "Sen SD";
    const char* pchName = strName.c_str();

    strcpy( const_cast<char*>( pchName ), "Ann" );

    return 0;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900