传统弱校HFUT的蒟蒻,真相只有一个

c++复习:指针&存储区

一、示例,数组存储在内存的栈区,栈还会存函数入口地址等信息,test()调用结束以后会释放ch的存储区,

因此可以看到p没有存到内容。

char * test()
{
    char ch[]="hello";
    cout<<"$:"<<&ch<<endl;
    return ch;
}
int main()
{
    char *p=test();////////////wrong!!
    cout<<"#:"<<&p<<endl;
   cout<<"*"<<p<<endl;
return 0; } /* $:0x6dfeca #:0x6dfefc
*:
*/

正确的方式:new出的空间存在内存的堆中

char * test()
{
    char *ch=new char[3];
    ch[0]='m';
    ch[1]='y';
    ch[2]='\0';
    cout<<"$:"<<&ch<<endl;
    return ch;
}
int main()
{
    char *p=test();
    cout<<"#:"<<&p<<endl;
    cout<<p<<endl;
    return 0;
}
/*
$:0x6dfecc
#:0x6dfefc
my
*/

二、常量数组p的内容不允许修改,存储在常量存储区

char * test()
{
    char ch[]="hello";
    ch[0]='H';
    char *p="world";
    p[0]='W';//wrong!!!
    return ch;
}
int main()
{
    test();
    return 0;
}

 

posted @ 2020-04-01 20:27  未名亚柳  阅读(233)  评论(0编辑  收藏  举报