C 动态内存分配
C 动态内存分配
在本教程中,您将学习使用标准库函数在 C 程序中动态分配内存:malloc()、calloc()、free() 和 realloc()。
如您所知,数组是固定数量值的集合。一旦声明了数组的大小,就无法更改。
有时您声明的数组的大小可能不足。要解决此问题,您可以在运行时手动分配内存。这在 C 编程中称为动态内存分配。
为了动态分配内存,库函数是 malloc()
, calloc()
, realloc()
和 free()
被使用。这些函数在 <stdlib.h>
中定义 头文件。
C malloc()
“malloc”这个名字代表内存分配。
malloc()
函数保留指定字节数的内存块。并且,它返回一个 void
的指针 可以转换成任何形式的指针。
malloc() 的语法
ptr = (castType*) malloc(size);
示例
ptr = (float*) malloc(100 * sizeof(float));
上面的语句分配了 400 字节的内存。这是因为 float
的大小 是 4 个字节。并且,指针 ptr 保存分配内存中第一个字节的地址。
表达式的结果是 NULL
内存无法分配时的指针。
C calloc()
名称“calloc”代表连续分配。
malloc()
函数分配内存并使内存未初始化,而 calloc()
函数分配内存并将所有位初始化为零。
calloc() 的语法
ptr = (castType*)calloc(n, size);
示例:
ptr = (float*) calloc(25, sizeof(float));
上面的语句在内存中为 float
类型的 25 个元素分配了连续的空间 .
C 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;
}
输出
Enter number of elements: 3
Enter elements: 100
20
36
Sum = 156
在这里,我们为 n 动态分配了内存 int
的数量 .
示例 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;
}
输出
Enter number of elements: 3
Enter elements: 100
20
36
Sum = 156
C 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:\n");
for(i = 0; i < n1; ++i)
printf("%pc\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:\n");
for(i = 0; i < n2; ++i)
printf("%pc\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
C语言