`
3895177
  • 浏览: 22595 次
社区版块
存档分类
最新评论

动态内存分配

    博客分类:
  • c++
 
阅读更多
#include <iostream>
using namespace std;
void mian()
{
	char* pc;
	int*  pi;
	//new 类型标示符
	pc =new char;
	*pc = 'a';
	cout<<*pc<<endl;
	//new 类型标示符(初始值)
	pi = new int(8);
	cout<<*pi<<endl;

	//new 类型标示符[内存单元个数]
	char* pStr= new char[20];
	char str[20];
	strcpy(pStr,"It is a string.");
	strcpy(str,"It is a string too.");
	cout<<pStr<<endl;
	cout<<str<<endl;

	//判断是否是有效的地址
	//如果成功,就返回有效内存地址
	//否则会返回0,
	//检查是否指针是否等于0就行
	if (pc)
	{
		delete pc;
	}
	if (pi)
	{
		delete pi;
	}
	if (pStr)
	{
		//释放数组空间,要带[],否则只是释放数组头元素
		delete []pStr;
	}
	
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics