首页 > 编程语言 > 详细

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

时间:2020-04-01 21:05:07      阅读:56      评论:0      收藏:0      [点我收藏+]

一、示例,数组存储在内存的栈区,栈还会存函数入口地址等信息,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;
}

 

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!