带有程序示例的 C 库中的 calloc() 函数
什么是 C 中的 calloc?
calloc() 在 C 中是一个函数,用于分配具有相同大小的多个内存块。它是一个动态内存分配函数,将内存空间分配给复杂的数据结构,如数组和结构,并返回一个指向内存的void指针。 Calloc 代表连续分配。
malloc 函数用于分配单个内存空间块,而 C 中的 calloc 函数用于分配多个内存空间块。 C 编程中由 calloc 分配的每个块的大小相同。
calloc() 语法:
ptr = (cast_type *) calloc (n, size);
- 上面C中calloc的语句示例用于分配n个相同大小的内存块。
- 分配内存空间后,所有字节都被初始化为零。
- 返回当前位于已分配内存空间第一个字节的指针。
每当分配内存空间出现错误(例如内存不足)时,都会返回一个空指针,如下面的 calloc 示例所示。
如何使用calloc
下面的 C 语言 calloc 程序计算等差数列的和。
#include <stdio.h> int main() { int i, * ptr, sum = 0; ptr = calloc(10, sizeof(int)); if (ptr == NULL) { printf("Error! memory not allocated."); exit(0); } printf("Building and calculating the sequence sum of the first 10 terms \ n "); for (i = 0; i < 10; ++i) { * (ptr + i) = i; sum += * (ptr + i); } printf("Sum = %d", sum); free(ptr); return 0; }
C 示例中 calloc 的结果:
Building and calculating the sequence sum of the first 10 terms Sum = 45
C语言