new和delete

  1 #include<iostream>
  2 using namespace std;
  3 #include<cstdlib>
  4 #include<string>
  5 #include<new>
  6 //new 类型==>(类型*)malloc(sizeof(类型))
  7 
  8 int main()
  9 {
 10         int* p = static_cast<int*>(malloc(sizeof(int)));
 11         int* q = new int;//不保证是0
 12         int* r = new int(888);
 13         cout<< *q <<","<<*r<<endl;
 14         int n; 
 15         cout<<"请输入一个整数:";
 16         cin>>n;
 17         int* a = new(nothrow) int[n];//申请空间返回数组最开始地址,不保证清零
 18         //用(nothrow)如果申请不成功返回指针为NULL
 19         if(NULL == a)
 20         {
 21                 cout<<n*sizeof(int)<<"申请失败"<<endl;

 22         }

23         else
 24         {
 25                 for(int i = 0;i<n;i++)
 26                 {
 27                         cout<<a[i]<<"  ";
 28                         if(a[i])
 29                         {
 30                                 cout<<flush;
 31                                 char c;
 32                                 cin>>c;
 33                         }
 34                 }
 35         }
 36         cout<<endl;
 37 
 38         delete r;r = NULL;
 39         delete q;q = NULL;
 40         delete[] a;a = NULL;
 41         free(p);//malloc申请的内存不要用delete p
 42         return 0;
 43 }
                         

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值