It doesn't work because str1 is pointing to a Constant string: I.e a read-only string. You cannot modify it!
cin is an input stream - you read from it into teh variable.
cout is an output stream - your write to it from a variable.
If you want to read a string from the user, try this:
char[100] text;
cin >> text;
cout << text << endl;
char * str1="hello world!";
cout<<endl<<str1;
str1 = "hello";
cout<<endl<<str1;
- str1 now is "Hello"
Yes - because you have moved the pointer to a different area of memory.
Instead of referring to a constant string "hello world!" terminated by a null character, it now points to a different constant string "Hello" (terminated by a null character). The original contents of the string are unchanged, you are just pointing at different memory (and you still can't overwrite it!)
Try this:
char* str1="hello world!";
char* str2 = str1;
cout<<endl<<str1;
str1 = "hello";
cout<<endl<<str1;
cout<<endl<<str2;
"I did not try to overwrite it. I just got wrong the line "you can not modify it". More interesting why compiler can not generate any error in this case."
Yes you did! :laugh:
char * str1="hello world!";
cin>>str1;
The
cin
tries to write whatever the user types into the memory pointed at by str1. This is an write operation, thus an attempt to overwrite the string content.
The compiler will not generate an error - it can't - because there is no way for it to know (in all cases) that the memory is read only:
char * str1="hello world!";
char[100] str2;
GetString(str2);
GetString(str1);
...
void GetString(char* pstr)
{
cin >> pstr;
}
The first call to GetString is fine, the second is a run time error.