您的位置:首页 > 编程语言 > C语言/C++

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

2015-08-13 17:14 387 查看


内存的申请与示范



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





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





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



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

#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;
}


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