1. 程式人生 > >C++ 動態記憶體

C++ 動態記憶體

動態記憶體在程式執行的時候動態的進行申請,記憶體生存期結束後釋放申請的記憶體

1、運算子new和new[]

pointer = new type     申請一個型別的動態資源 pointer = new type [number_of_elements]   申請一個型別陣列的動態資源

int * foo;
foo = new int [5];

如果當分配動態記憶體失敗時,將丟擲bad_alloc型別的異常,需要利用異常捕獲去獲取異常

p = new (nothrow) int[i];  //當動態記憶體申請錯誤時,丟擲空指標,程式繼續執行
	if (p == nullptr)
	{
		cout << "error:memory could not be allocated";
	}

當p申請失敗是返回一個空指標進行判斷動態記憶體是否申請成功

2、運算子delete和delete[]

delete pointer;
delete[] pointer;釋放申請的動態記憶體資源,對應new和new[]
#include <iostream>
using namespace std;

#include <new>
int main()
{
	int i, n;
	int * p;
	cout << "how many numbers would you like to type?";
	cin >> i;
	p = new (nothrow) int[i];  //當動態記憶體申請錯誤時,丟擲空指標,程式繼續執行
	if (p == nullptr)
	{
		cout << "error:memory could not be allocated";
	}
	else{
		for ( n = 0; n < i; n++)
		{
			cout << "enter number:";
			cin >> p[n];
		}
		cout << "you have entered:";
		for ( n = 0; n < i; n++)
		{
			cout << p[n] << "-";
		}
		delete[] p;
	}
	return 0;
}

3、C++和C的區別

C++的動態記憶體申請和釋放使用關鍵字:new和delete

C語言的動態記憶體申請和釋放使用關鍵字:malloc、calloc、realloc和free(函式包含在有檔案<stdlib>中)——這些函式在C++同樣可以使用,但是儘量不要混用

       void *malloc(size_t size);        void free(void *ptr);        void *calloc(size_t nmemb, size_t size);        void *realloc(void *ptr, size_t size);

int *p;

      p = (int *)malloc(sizeof(int));