C 庫函數(shù) - calloc()

C 標(biāo)準(zhǔn)庫 - <stdlib.h> C 標(biāo)準(zhǔn)庫 - <stdlib.h>

描述

C 庫函數(shù) void *calloc(size_t nitems, size_t size) 分配所需的內(nèi)存空間,并返回一個指向它的指針。malloccalloc 之間的不同點是,malloc 不會設(shè)置內(nèi)存為零,而 calloc 會設(shè)置分配的內(nèi)存為零。

聲明

下面是 calloc() 函數(shù)的聲明。

void *calloc(size_t nitems, size_t size)

參數(shù)

  • nitems -- 要被分配的元素個數(shù)。
  • size -- 元素的大小。

返回值

該函數(shù)返回一個指針,指向已分配的內(nèi)存。如果請求失敗,則返回 NULL。

實例

下面的實例演示了 calloc() 函數(shù)的用法。

#include <stdio.h>
#include <stdlib.h>

int main()
{
   int i, n;
   int *a;

   printf("要輸入的元素個數(shù):");
   scanf("%d",&n);

   a = (int*)calloc(n, sizeof(int));
   printf("輸入 %d 個數(shù)字:\n",n);
   for( i=0 ; i < n ; i++ ) 
   {
      scanf("%d",&a[i]);
   }

   printf("輸入的數(shù)字為:");
   for( i=0 ; i < n ; i++ ) {
      printf("%d ",a[i]);
   }
   
   return(0);
}

讓我們編譯并運行上面的程序,這將產(chǎn)生以下結(jié)果:

要輸入的元素個數(shù):3
輸入 3 個數(shù)字:
22
55
14
輸入的數(shù)字為:22 55 14

C 標(biāo)準(zhǔn)庫 - <stdlib.h> C 標(biāo)準(zhǔn)庫 - <stdlib.h>