C-standard-library-c-function-calloc
提供:Dev Guides
Cライブラリ関数-calloc()
説明
Cライブラリ関数 void calloc(size_t nitems、size_t size)は、要求されたメモリを割り当て、それへのポインタを返します。 *malloc と calloc の違いは、mallocがメモリをゼロに設定しないのに対し、callocは割り当てられたメモリをゼロに設定することです。
宣言
以下はcalloc()関数の宣言です。
void *calloc(size_t nitems, size_t size)
パラメーター
- nitems -これは割り当てられる要素の数です。
- サイズ-これは要素のサイズです。
戻り値
この関数は、割り当てられたメモリへのポインタを返します。リクエストが失敗した場合は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",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