zoukankan      html  css  js  c++  java
  • 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]='';
        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;
    }
  • 相关阅读:
    MongodDB数据库安装和简单使用
    比较运算符
    Java习题
    JavaScript示例
    Java面向过程练习题7
    Java面向过程练习题6
    倒金字塔
    包含contains
    String 比较
    单词表
  • 原文地址:https://www.cnblogs.com/dzzy/p/12615284.html
Copyright © 2011-2022 走看看