内存的申请与示范
*****************************************************************************************
*****************************************************************************************
*****************************************************************************************
********************************************************************************************
#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字符串到
分配的堆中的内存中,打印字符串,最后释放内存
在堆中申请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;
}