首页 > 其他 > 详细

075.程序的内存模型-new运算符

时间:2021-09-06 05:00:23      阅读:18      评论:0      收藏:0      [点我收藏+]
#include <iostream>
using namespace std;

//1.new的基本语法
int* func()
{
    //在堆区创建整数数据
    //new返回是 该数据类型的指针
    int* p = new int(10);
    return p;
}

void test01()
{
    int* p = func();
    cout << *p << endl;
    cout << *p << endl;
    cout << *p << endl;
    //堆区的数据由程序员管理开辟,程序员释放
    //如果想要释放堆区的数据,利用关键字delete
    delete p;
    //cout << *p << endl;//保存
}

//2.在堆区利用new开辟数组
void test02()
{
    //创建10个整型的数组,在堆区
    int* arr = new int[10];//代表数组有10个元素
    for (size_t i = 0; i < 10; i++)
    {
        arr[i] = i + 100;//给10个元素赋值100~109

    }

    for (size_t i = 0; i < 10; i++)
    {
        cout << arr[i] << endl;
    }
    //释放堆区数组
    //释放数组的时候,要加[]才可以
    delete[]arr;
}
int main()
{
    test01();
    system("pause");
    return 0;
}

 

075.程序的内存模型-new运算符

原文:https://www.cnblogs.com/ceovs/p/15228131.html

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