I just started learning the relationship between pointers and arrays. What I read from this thread(What is the difference between char a[] = ?string?; and char *p = ?string?;?) is the string pointed by the pointer can not be changed. But in the following piece of code, I can change the string pointed by pa from abc to abd without any problem.
int main()
{
char *pa;
pa="abc";
cout<<pa<<endl<<endl;
pa="abd";
cout<<pa<<endl<<endl;
return 0;
}
However, it does not work in this piece of code. Can someone explain the difference to me? Thank you very much!!
int main()
{
char *pc;
pc="abc";
cout<<pc<<endl<<endl;
*(pc+2)='d';
cout<<pc<<endl<<endl;
return 0;
}
*(pc+2)) to access the memory of the 3rd char, but ya, undefined behavior still since you are using a string literal. Those are supposed to be constants and are not to be modified. I suggest you skipchar*and graduate tostd::stringbtwstd::string? The pointer stuff is confusing.std::string str= "abc"; str[2] = "d";I havent used C++ in a while so that might have some minor errors. As you can see the string API is more natural and easy to use/understand