Just My Life & My Work

我們使用變數時,可以直接在程式碼中宣告個數(陣列),然而很多時候不曉得需要用到多少個變數,為了節省記憶體空間起見,我們就需要用動態的方式來配置記憶體

在此我實驗了C和C++的指令:

/**
	Theme: Dynamic Allocation of Memory
	Compiler: Dev C++ 4.9.9.2
	Date: 100/04/22
	Author: ShengWen
	Blog: https://cg2010studio.wordpress.com/
*/
#include<iostream>
using namespace std;
const int ROUND=5;
int main(){
	int *n1, *n2, *n3, *n4;
	//C language
	n1=(int*)malloc(sizeof(int)*ROUND);
	n2=(int*)calloc(ROUND,sizeof(int));
	for(int n=0; n<ROUND; n++){
		cout<<"n1+"<<n<<"("<<n1+n<<"): "<<*(n1+n)<<endl;	}
	cout<<endl;
	for(int n=0; n<ROUND; n++){
		cout<<"n2+"<<n<<"("<<n2+n<<"): "<<*(n2+n)<<endl;	}
	cout<<endl;
	//C++ language
	n3=new int[ROUND];
	n4=new int(0);//error n4=new int[ROUND](0);
	
	cout<<"//original n3"<<endl;
	for(int n=0; n<ROUND; n++){
		cout<<"n3+"<<n<<"("<<n3+n<<"): "<<*(n3+n)<<endl;	}
	cout<<endl;
	for(int n=0; n<1; n++){
		cout<<"n4+"<<n<<"("<<n4+n<<"): "<<*(n4+n)<<endl;	}
	cout<<endl;
	free(n1); 
	free(n2);
	for(int n=0; n<ROUND; n++){
		*(n3+n)=n;	}
	
	cout<<"//modified n3"<<endl;
	for(int n=0; n<ROUND+1; n++){
		cout<<"n3+"<<n<<"("<<n3+n<<"): "<<*(n3+n)<<endl;	}
	cout<<endl;	
	delete [] n3;
	delete n4; 
	n3=new int[ROUND+1];

	cout<<"//fianl n3"<<endl;
	for(int n=0; n<ROUND+1; n++){
		cout<<"n3+"<<n<<"("<<n3+n<<"): "<<*(n3+n)<<endl;	}
	cout<<endl;	

	system("pause");
	return EXIT_SUCCESS;	
}

在此先解說c的動態配置記憶體函式malloccalloc的差異,除了函式的參數不一樣之外,還有前者不會做初始化,而後者會做初始化。最後歸還記憶體時,使用free函式。

c++則使用new,它無法在配置大量(陣列)時初始化,單一型態變數還ok。歸還記憶體時採用delete,實驗了有無加[]效果好像一樣……

看執行結果如何:

n1+0(0x33ed8): 197288
n1+1(0x33edc): 197288
n1+2(0x33ee0): 0
n1+3(0x33ee4): 0
n1+4(0x33ee8): 0

n2+0(0x33ef8): 0
n2+1(0x33efc): 0
n2+2(0x33f00): 0
n2+3(0x33f04): 0
n2+4(0x33f08): 0

//original n3
n3+0(0x33f18): 197224
n3+1(0x33f1c): 197224
n3+2(0x33f20): 0
n3+3(0x33f24): 0
n3+4(0x33f28): 0

n4+0(0x33e70): 0

//modified n3
n3+0(0x33f18): 0
n3+1(0x33f1c): 1
n3+2(0x33f20): 2
n3+3(0x33f24): 3
n3+4(0x33f28): 4
n3+5(0x33f2c): 0

//fianl n3
n3+0(0x33f18): 212728
n3+1(0x33f1c): 1
n3+2(0x33f20): 2
n3+3(0x33f24): 3
n3+4(0x33f28): 4
n3+5(0x33f2c): 0

請按任意鍵繼續 . . .

n1和n2分別為malloccalloc動態配置記憶體的結果。n3和n4則是使用new。在此特別做了n3歸還再配置的動作,結果n3前面5個int空間依然為未歸還之前的記憶體位址,而值有可能還會殘留,所以使用new配置記憶體給變數指標後,還要記得做初始化的動作!

隨意留個言吧:)~

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料

標籤雲