It appears that if you define one string and store the value of the string in another string and you try to change one of the strings, you'll end up changing both of them(as in the image). My question is why does this happen and is there any right way of doing it?
1 Answer
It happens because a "string" is actually a pointer to a char array that ends in a null terminator, so when you do "s1 = s2" you are simply pointing s2
to the same array as s1
.
This is covered in the Week 4 Lecture. Here are the notes for that lecture, which include code samples.