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

时间:2020-04-01
本文章向大家介绍c++复习:指针&存储区,主要包括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;
}

原文地址:https://www.cnblogs.com/dzzy/p/12615284.html