前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >指针与自由存储空间

指针与自由存储空间

作者头像
用户8247415
发布2021-04-13 16:11:21
1.4K0
发布2021-04-13 16:11:21
举报
文章被收录于专栏:网页前端网页前端
long * fellow; // create a pointer-to-long
*fellow = 223323; // place a value in never-never land

使用new来分配内存! 在大型项目中有巨大作用,减少内存!

在这里插入图片描述
在这里插入图片描述
int * pn = new int;
在这里插入图片描述
在这里插入图片描述
typeName * pointer_name = new typeName;

看一串代码:

// use_new.cpp -- using the new operator
#include 
int main()
{
    using namespace std;
    int nights = 1001;
    int * pt = new int;  // allocate space for an int
    *pt = 1001;          // store a value there

    cout << "nights value = ";
    cout << nights << ": location " << &nights << endl;
    cout << "int ";
    cout << "value = " << *pt << ": location = " << pt << endl;
    double * pd = new double; // allocate space for a double
    *pd = 10000001.0; // store a double there

    cout << "double ";
    cout << "value = " << *pd << ": location = " << pd << endl;
    cout << "location of pointer pd: " << &pd << endl;
    cout << "size of pt = " << sizeof(pt);
    cout << ": size of *pt = " << sizeof(*pt) << endl;
    cout << "size of pd = " << sizeof pd;
    cout << ": size of *pd = " << sizeof(*pd) << endl;
    return 0;
}

输出后:

nights value = 1001: location 0028F7F8
int value = 1001: location = 00033A98
double value = 1e+007: location = 000339B8
location of pointer pd: 0028F7FC
size of pt = 4: size of *pt = 4
size of pd = 4: size of *pd = 8
在这里插入图片描述
在这里插入图片描述

字节数的差别哦!

delete释放内存

int * ps = new int;   // allocate memory with new
. . .                 // use the memory
delete ps;            // free memory with delete when done
int * ps = new int;   // ok
delete ps;            // ok
delete ps;            // not ok now
int jugs = 5;         // ok
int * pi = &jugs;     // ok
delete pi;            // not allowed, memory not allocated by new
int * ps = new int; // allocate memory
int * pq = ps;      // set second pointer to same block
delete pq;          // delete with second pointer
在这里插入图片描述
在这里插入图片描述
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-03-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档