1. 程式人生 > >VS2010 C++ 學習筆記(二) 記憶體管理 new delete

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