道亦无名 2014-12-02 03:14 采纳率: 100%
浏览 1900
已采纳

C语言中的指针和数组的初始化

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);

}

为什么会出现这个问题呢?

  • 写回答

3条回答 默认 最新

  • 91program 博客专家认证 2014-12-02 09:01
    关注

    pmessage 指向的 "now is the time"; 是存贮在常量区的,所以其内容不能修改。

    char amessage[] 定义时,编译器为 amessage 分配了空间,然后将字符串复制到其中,这种从 堆栈上 分配来的空间就可以修改。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?