malloc、calloc:
程式中,資源之間的互用關係錯綜複雜,不想讓 [函式執行過後,配置的空間就會自動清除]。
所以使用 malloc 、calloc可自行規範記憶體空間,但用完需要自行釋放掉(free)
如以下程式: malloc、calloc差異
int *p = malloc(sizeof(int));
malloc 為設定動態記憶體,大小為int(4byte),但不初始化內容值)
int *p = calloc(1, sizeof(int));
calloc 為設定動態記憶體,大小為int(4byte),但初始化內容值(0)
如 picture.1所示,宣告內存中為5個元素分配連續的空間,每個元素的大小均為int。
Free
釋放記憶體空間,如 picture.2 所示。
Code:
#include <stdio.h>
#include <stdlib.h>
int main(){
int i, n;
int* a;
n = 10;
a = (int*)calloc(n, sizeof(int));
printf(“Enter %d numbers: \r\n”,n);
printf(“The numbers entered are: \r\n”);
for (i = 0; i < n; i++) {
printf(“%d value is %d \r\n”, i, *(a+i));
}
free(a);
return(0);
}