char a[]="abcdef";
char *p ="cdefg";
a[1]='A';
p[1]='A';
这段代码有什么问题?
#include
int main()
{
char amessage[]="now is the time";
char *pmessage = "now is the time"; /*字符串常量,不能更改*/
amessage[1] = 'A';
pmessage[2] = 'B';
printf("%s\n",amessage);
printf("%s",pmessage);
while(1);
}
为什么会出现这个问题呢?
pmessage 指向的 "now is the time"; 是存贮在常量区的,所以其内容不能修改。
char amessage[] 定义时,编译器为 amessage 分配了空间,然后将字符串复制到其中,这种从 堆栈上 分配来的空间就可以修改。
在这里, char *pmessage其实是cosnt char *pmessage;就是常量字符串,当然是不能改变了,如果你要改变字符串,你应该这么定义
char pmessage[] = "now is the time";
char a[]="abcdef"; 内容保存在常量区 不能更改
char *p ="cdefg"; 内容保存在栈空间上,可以修改