目录

void *calloc(size_t nitems, size_t size)

描述 (Description)

C库函数void *calloc(size_t nitems, size_t size)分配请求的内存并返回指向它的指针。 malloccalloc的区别在于malloc没有将内存设置为零,而calloc将分配的内存设置为零。

声明 (Declaration)

以下是calloc()函数的声明。

void *calloc(size_t nitems, size_t size)

参数 (Parameters)

  • nitems - 这是要分配的元素数。

  • size - 这是元素的大小。

返回值 (Return Value)

此函数返回指向已分配内存的指针,如果请求失败,则返回NULL。

例子 (Example)

以下示例显示了calloc()函数的用法。

#include <stdio.h>
#include <stdlib.h>
int main () {
   int i, n;
   int *a;
   printf("Number of elements to be entered:");
   scanf("%d",&n);
   a = (int*)calloc(n, sizeof(int));
   printf("Enter %d numbers:\n",n);
   for( i=0 ; i < n ; i++ ) {
      scanf("%d",&a[i]);
   }
   printf("The numbers entered are: ");
   for( i=0 ; i < n ; i++ ) {
      printf("%d ",a[i]);
   }
   free( a );
   return(0);
}

让我们编译并运行上面的程序,它将产生以下结果 -

Number of elements to be entered:3
Enter 3 numbers:
22
55
14
The numbers entered are: 22 55 14
↑回到顶部↑
WIKI教程 @2018