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("%u\n",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("%u\n", ptr + i);
free(ptr);
return 0;
}
運行該程序時,輸出為:
輸入大小:2
先前分配的內存的地址:26855472
26855476
輸入新的尺寸:4
新分配的內存地址:26855472
26855476
26855480
26855484
總結
malloc動態分配內存,不初始化
int n, *ptr = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
如果無法分配內存,則返回NULL
calloc動態分配內存,初始化所有bit為0
int n, *ptr = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
如果無法分配內存,則返回NULL
free釋放內存
free(ptr);
realloc重新分配內存
ptr = realloc(ptr, n * sizeof(int));