C 库中的 calloc() 函数及其程序示例

C 语言中的 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