原文: https://www.programiz.com/c-programming/c-dynamic-memory-allocation
如您所知,数组是固定数量的值的集合。 声明数组的大小后,您将无法更改它。
有时,您声明的数组的大小可能不足。 要解决此问题,可以在运行时手动分配内存。 这在 C 编程中称为动态内存分配。
为了动态分配内存,使用了malloc(),calloc(),realloc()和free()这些库函数。 这些函数在<stdlib.h>头文件中定义。
名称malloc代表内存分配。
malloc()函数保留指定字节数的内存块。 并且,它返回void的指针,可以将其转换为任何形式的指针。
ptr = (castType*) malloc(size);示例
ptr = (float*) malloc(100 * sizeof(float));上面的语句分配了 400 个字节的内存。 这是因为float的大小为 4 个字节。 并且,指针ptr保存分配的内存中第一个字节的地址。
如果无法分配内存,则表达式将产生NULL指针。
名称calloc代表连续分配。
malloc()函数分配内存,并保留未初始化的内存。 而calloc()函数分配内存并将所有位初始化为零。
ptr = (castType*)calloc(n, size);示例:
ptr = (float*) calloc(25, sizeof(float));上面的语句在内存中为float类型的 25 个元素分配了连续的空间。
使用calloc()或malloc()创建的动态分配内存不会自行释放。 您必须显式使用free()释放空间。
free(ptr);该语句释放ptr指向的内存中分配的空间。
// 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个int的数量动态分配了内存。
// 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;
} 如果动态分配的内存不足或超出要求,则可以使用realloc()函数更改先前分配的内存大小。
ptr = realloc(ptr, x);在此,以新的大小x重新分配ptr。
#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;
}运行该程序时,输出为:
Enter size: 2
Addresses of previously allocated memory:26855472
26855476
Enter the new size: 4
Addresses of newly allocated memory:26855472
26855476
26855480
26855484