2018年6月14日 星期四

Dynamic Memory 動態內存

  • malloc, calloc, realloc, free
  1. malloc-安排空間 ,未安排初始值 int *ptr1=malloc(1000*sizeof(int));
  2. calloc-安排空間,安排初始值 0 int *ptr2=calloc(1000,sizeof(int));
  3. realloc-重新安排指定(*)空間 int *ptr3=realloc(ptr2,sizeof(int)*2);
  4. free(ptr);釋放空間

  • 二維陣列
(一)分別分配好內存,再把分配好的指針內存分給本體,要一個一個分給本體,因為*pData的第一個到最後一個(一列n個)

int **Array, *pData; 

int m,n,i; 
Array = (int**)malloc(m*sizeof(int *)); 
pData = (int*)malloc(m*n*sizeof(int)); "總數"
for(i = 0; i < m; i++, pData += n)
Array[i] = pData; "pData,pData+n,pData+2n...+pData+mn"
"之所以要分別劃分給他的原因是空間不連續,但是往下排卻連續的原因"

for(int j=0;j
free(Array[j]);
}
free (Array);
return 0;只需做兩次malloc,free只要free Array和Array[0]就可以了

(二)(x)

int i;
int **Array;
Array = (int **)malloc(m*sizeof(void *));
for (i = 0; i < m; i++)
Array = (int *)malloc(n*sizeof(int *));

這樣子的配置方式要做很多次的malloc,,並容易造成記憶體碎片化(memory fragment)

(三)

int i;
int **Array, *pData;
Array = (int **)malloc(m*sizeof(int *)+m*n*sizeof(int));
for (i = 0, pData = (int *)(Array+m); i < m; i++, pData += n)"指針先指向一維陣列的指針,再分配n個int"
Array[i]=pData;
free (Array);這樣是最簡便的寫法 只要mallocㄧ次完成,free只要free Array即可
  • new, delete(c++特有)
  1. new  安排指針給他,讓他可以再安排指針給別人

沒有留言:

張貼留言

Ethereum- Learn Solidity step by step

Common Function Types: public: Anyone can call this function,but it isn't really used for any type of security per se. priv...