12-【每天亿点点C++,简单又有趣儿】栈区、堆区

栈区

栈区数据的注意事项

  • 栈区数据由编译器管理开辟释放
  • 不要返回局部变量的地址
#include<iostream>
#include<string>
using namespace std;

int * funcc()
{
    int a = 10;//局部变量存放在栈区,栈区数据执行完自动释放
    return &a;//返回局部变量的地址
}
int main()
{
    int b = 0;
    int *p = funcc();
    cout << p << endl;
    //cout << *p << endl;//第一次可以打印正确的数字,是因为编译器会给你保留
    //cout << *p << endl;
}

堆区

#include<iostream>
#include<string>
using namespace std;


int * fuv();
void test01();
void test02();


// 程序运行期间由程序员开辟的内存分区
int main_rgvfdc()
{
    test01();
    test02();

}
//在堆区开辟数据
int * fuv()
{
    //利用new,开辟到堆区
    int * p = new int(10);
    return p;
}
//释放堆区内存
void test01()
{
    int * p = fuv();
    cout << *p << endl;
    delete p; //内存已经被释放
}
// 在堆区创建数组
void test02()
{
    int * arr = new int[10]; //开辟
    for (int i = 0 ;i<10;i++)
    {
        arr[i] = i+100;
    }
    for (int i = 0 ;i<10;i++)
    {
        cout << arr[i] << endl;
    }
    delete[] arr;//释放
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/magic_shuang/article/details/107549813
今日推荐