中文字幕一区二区人妻电影,亚洲av无码一区二区乱子伦as ,亚洲精品无码永久在线观看,亚洲成aⅴ人片久青草影院按摩,亚洲黑人巨大videos

C庫中的calloc()函數(shù)及其示例

發(fā)布于:2021-02-07 16:28:15

0

456

0

C calloc() 示例 編程語言

C語言中的calloc是什么?

C語言中的calloc()是用于分配具有相同大小的多個內(nèi)存塊的函數(shù)。它是一種動態(tài)內(nèi)存分配功能,可將內(nèi)存空間分配給復雜的數(shù)據(jù)結構(例如數(shù)組和結構),并返回指向內(nèi)存的空指針。Calloc代表連續(xù)分配。

Malloc函數(shù)用于分配單個存儲空間塊,而C語言中的calloc函數(shù)用于分配多個存儲空間塊。C語言編程中calloc分配的每個塊的大小相同。

calloc()語法:

ptr = (cast_type *) calloc (n, size);

  • 上面的C語言中的calloc語句示例用于分配n個相同大小的內(nèi)存塊。

  • 分配內(nèi)存空間后,所有字節(jié)都初始化為零。

  • 返回當前位于分配的存儲空間的第一個字節(jié)的指針。

每當分配內(nèi)存空間的錯誤(例如內(nèi)存不足)時,都會返回空指針,如下面的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