2.3 KiB
2.3 KiB
C 中的calloc()函数
原文:https://overiq.com/c-programming-101/the-calloc-function-in-c/
最后更新于 2020 年 7 月 27 日
c 提供了另一个动态分配内存的函数,它有时比 malloc()函数更好。它的语法是:
语法: void *calloc(size_t n, size_t size);
它接受两个参数第一个参数是元素的数量,第二个参数是元素的大小。假设我们想为5整数分配内存,在这种情况下,5是元素的数量,即n,每个元素的大小是4字节(可能因系统而异)。以下是如何使用calloc()为 5 个整数分配内存。
int *p;
p = (int*)calloc(5, 4);
这将从堆中分配20字节的连续内存空间,并将第一个分配字节的地址分配给指针变量p。
以下是如何使用malloc()功能实现同样的事情:
int *p;
p = (int*)malloc(5 * 4);
为了使我们的程序可移植性和可读性更强sizeof()运算符与calloc()一起使用。
int *p;
p = (int*)calloc(5, sizeof(int));
那么除了争论的数量之外calloc()和malloc()还有其他区别吗?
calloc()和malloc()函数的区别在于malloc()分配的内存包含垃圾值,而calloc()分配的内存总是初始化为0。
以下程序使用calloc()创建动态(运行时大小可以变化)一维数组。
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p, i, n;
printf("Enter the size of the array: ");
scanf("%d", &n);
p = (int*)calloc(n, sizeof(int));
if(p==NULL)
{
printf("Memory allocation failed");
exit(1); // exit the program
}
for(i = 0; i < n; i++)
{
printf("Enter %d element: ", i);
scanf("%d", p+i);
}
printf("\nprinting array of %d integers\n\n", n);
// calculate sum
for(i = 0; i < n; i++)
{
printf("%d ", *(p+i));
}
// signal to operating system program ran fine
return 0;
}
**预期输出:**第一次运行:
Enter the size of the array: 5
Enter 0 element: 13
Enter 1 element: 24
Enter 2 element: 45
Enter 3 element: 67
Enter 4 element: 89
printing array of 5 integers
13 24 45 67 89
第二次运行:
Enter the size of the array: 2
Enter 0 element: 11
Enter 1 element: 34
printing array of 2 integers
11 34