VS2010 C++ 学习笔记(二) 内存管理 new delete





内存的申请与示范 

*****************************************************************************************






*****************************************************************************************


***************************************************************************************** 



********************************************************************************************
#include <stdlib.h>
#include <iostream>
using namespace std;

int main(void)
{      	
	int *p = new int(20); 
	//等价于 int *p = new int;
    //              *p = 20; 
	if (NULL == p)
	{
		cout << "new error" << endl;
		system("pause");
		return 0;
	}
	cout << *p << endl;
	delete p;
	p = NULL;
	system("pause");
	return 0;
}

*******************************************************************************
#include <stdlib.h>
#include <iostream>
using namespace std;

int main(void)
{      	
	int *p = new int[1000];
	if (NULL == p)
	{
		cout << "new error" << endl;
	}
	p[0] = 4;
	p[1] = 8;
	p[2] = 7;
	cout << p[0] << "," << p[1] << ","  << p[2]  << ","  << p[56] << endl;
	delete []p; //注意  p[56]会出现随机值。因为数组未初始化。
	p = NULL;
	system("pause");
	return 0;
}






***********************************************************************
  单元巩固
 在堆中申请100个char类型的内存,拷贝Hello imooc字符串到
 分配的堆中的内存中,打印字符串,最后释放内存
 在堆中申请100个char类型的内存,拷贝Hello imooc字符串到
 分配的堆中的内存中,打印字符串,最后释放内存

/*********************************************************************************************
 单元巩固
 在堆中申请100个char类型的内存,拷贝Hello imooc字符串到
 分配的堆中的内存中,打印字符串,最后释放内存
 **********************************************************************************************/


#include <stdlib.h>
#include <iostream>
using namespace std;

int main(void)
{      	
	char *strp = new char[100];
	strcpy(strp, "Hello michael");
	cout << strp << endl;
	delete []strp;
	strp = NULL;
	system("pause");
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值