C語言動態記憶體分配
- 2019 年 10 月 27 日
- 筆記
C動態記憶體分配
數組是固定數量的值的集合,在聲明數組的大小之後,無法更改。有時,數組大小可能不夠,就需要動態擴容。解決此問題,可以在運行時手動分配記憶體。這在C編程中稱為動態記憶體分配。
動態分配存儲器涉及到的庫函數有
-
malloc()
-
calloc()
-
realloc()
-
free()
這些函數在<stdlib.h>
頭文件中定義。
1.malloc()
名稱「 malloc」代表記憶體分配,memory allocation。
該malloc()
函數保留指定位元組數的記憶體塊。並且,它返回一個指針的void
可鑄造成任何形式的指針。
malloc()的語法
ptr = (castType*) malloc(size);
例
ptr = (int*) malloc(100 * sizeof(float));
上面的語句分配了400個位元組的記憶體。這是因為float
的大小為4個位元組。並且,指針ptr保存分配的存儲器中的第一個位元組的記憶體地址。
如果無法分配記憶體,則表達式將產生一個NULL
指針。
2.calloc()
名稱「 calloc」代表連續分配,contiguous allocation。
malloc()
函數分配記憶體,但不初始化記憶體。而calloc()
函數分配記憶體並將所有位初始化為零。
calloc()的語法
ptr = (castType*)calloc(n, size);
例:
ptr = (float*) calloc(25, sizeof(float));
上面的語句為float
類型的25個元素在記憶體中分配了連續的空間。
3.free()
使用calloc()
或malloc()
不單獨釋放創建的動態分配記憶體,必須明確使用free()
釋放空間。
free()的語法
free(ptr);
該語句釋放由指向的記憶體中分配的空間ptr
。
示例1: malloc()和free()
// Program to calculate the sum of n numbers entered by the user #include <stdio.h> #include <stdlib.h> int main() { int n, i, *ptr, sum = 0; printf("Enter number of elements: "); scanf("%d", &n); ptr = (int*) malloc(n * sizeof(int)); // if memory cannot be allocated if(ptr == NULL) { printf("Error! memory not allocated."); exit(0); } printf("Enter elements: "); for(i = 0; i < n; ++i) { scanf("%d", ptr + i); sum += *(ptr + i); } printf("Sum = %d", sum); // deallocating the memory free(ptr); return 0; }
在這裡,我們已為n個數字動態分配了記憶體
示例2: calloc()和free()
// Program to calculate the sum of n numbers entered by the user #include <stdio.h> #include <stdlib.h> int main() { int n, i, *ptr, sum = 0; printf("Enter number of elements: "); scanf("%d", &n); ptr = (int*) calloc(n, sizeof(int)); if(ptr == NULL) { printf("Error! memory not allocated."); exit(0); } printf("Enter elements: "); for(i = 0; i < n; ++i) { scanf("%d", ptr + i); sum += *(ptr + i); } printf("Sum = %d", sum); free(ptr); return 0; }
4.realloc()
如果動態分配的記憶體不足或超出要求,則可以使用該realloc()
功能更改以前分配的記憶體的大小。
realloc()的語法
ptr = realloc(ptr, x);
在這裡,ptr以新的大小x重新分配。
示例3: realloc()
#include <stdio.h> #include <stdlib.h> int main() { int *ptr, i , n1, n2; printf("Enter size: "); scanf("%d", &n1); ptr = (int*) malloc(n1 * sizeof(int)); printf("Addresses of previously allocated memory: "); for(i = 0; i < n1; ++i) printf("%un",ptr + i); printf("nEnter the new size: "); scanf("%d", &n2); // rellocating the memory ptr = realloc(ptr, n2 * sizeof(int)); printf("Addresses of newly allocated memory: "); for(i = 0; i < n2; ++i) printf("%un", ptr + i); free(ptr); return 0; }
運行該程式時,輸出為:
輸入大小:2 先前分配的記憶體的地址:26855472 26855476 輸入新的尺寸:4 新分配的記憶體地址:26855472 26855476 26855480 26855484