new和delete【C++】

(1)例子 用new分配整型内存单元

#include "stdafx.h"
#include <iostream>
using namespace std;

{

          int  *p=NULL;

          p=new int;    //用new申请一个存放int类型数据的内存单元,

          cout<<"*p"<<*p<<endl;  

          system("pause")

          return 0;

}


(2)注意的是new和int在使用时应该成对使用

 例子 用new和delete动态分配内存单元

#include "stdafx.h"
#include <iostream>
using namespace std;

{

          int  *p=NULL;

          p=new int;

          cout<<"*p"<<*p<<endl;

          delete p;    //释放内存

          p=NULL;   //设置为空指针

          system("pause")

          return 0;

}

(3)new也可以在申请内存单元的同时进行初始化

语法如下   指针变量=new 数据类型 (初值)

                 p=new int (5);

                 delete p;

则会输出 *p=5。

(4)用new也可以分配数组空间解决多个连续的变量存储

语法如下  指针变量=new 数据类型 【初值】

                p=new int【1000】;

               `````````````````````````

               delete  [p] ;


发布了36 篇原创文章 · 获赞 17 · 访问量 6274

猜你喜欢

转载自blog.csdn.net/qq_39248307/article/details/77962728