您的位置:首页 > 其它

动态内存分配

2013-10-04 16:41 260 查看
#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;
}

}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: