为什么我能够更改指针p
中的元素,但不是指针r
中的元素?我猜它必须做指针的属性。指向字符串的指针无法更改字符
将p[2]
更改为w
使Gowdbye。更改r
崩溃代码。
p
的地址是0x69fee0
。
r
的地址是0x69fedc
。
两者在for循环中都有相同的输出(除了'Goodbye'结束后的垃圾数据)。
int main()
{
char q[]="Goodbye";
char* p = q;
char* r = "Goodbye";
cout<<"Address of p: "<<&p<<endl;
cout<<"Address of r: "<<&r<<endl;
for(int i = 0; i<10; i++)
{
cout<<"P["<<i<<"]: "<<p[i]<<endl;
cout<<"R["<<i<<"]: "<<r[i]<<endl;
}
p[2]='w';
cout<<p<<endl;
r[2]='w';
cout<<r<<endl;
return 0;
}
不能保证字符串文字将被放置在“只读存储器”中。 C++标准只是说试图修改一个字符串会导致未定义的行为。 –