C庫函數 void *calloc(size_t nitems, size_t size) 分配請求的記憶體,並返回一個指向它的指針。的malloc和calloc的區別是,malloc不設置記憶體calloc為零,其中作為分配的記憶體設置為零。
聲明
以下是calloc() 函數的聲明。
void *calloc(size_t nitems, size_t size)
參數
-
nitems -- 這是要分配的元素數。
-
size -- 這是元素的大小。
返回值
這個函數返回一個指針分配的記憶體,或NULL如果請求失敗。
例子
下麵的例子顯示了釋放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); 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]); } return(0); }
讓我們編譯和運行上面的程式,這將產生以下結果:
Number of elements to be entered:3 Enter 3 numbers: 22 55 14 The numbers entered are: 22 55 14
上一篇:
strtoul() - C語言庫函數
下一篇:
free() - C語言庫函數