ホームC言語Tips集配列・メモリ領域 ≫ メモリ領域を確保し,その領域を0で初期化する

C言語Tips集 - メモリ領域を確保し,その領域を0で初期化する

C言語でメモリ領域を動的に確保し,その領域を 0 で初期化するには stdlib.hcalloc 関数を使用します.

calloc

#include <stdlib.h>
void *calloc(
    size_t nmemb,
    size_t size
);

calloc 関数は,size バイトの大きさを持つオブジェクトが nmemb 個分入るメモリ領域を確保し,その領域のすべてのビットを 0 で初期化する関数です. メモリ領域の確保に成功した場合は,そのメモリ領域へのポインタを返し,失敗した場合は空ポインタ (NULL) を返します.

calloc 関数で確保したメモリ領域は,使用後 free 関数で解放します.

C言語サンプルプログラム

以下に calloc 関数を使用してメモリ領域を動的に確保するサンプルプログラムを示します.

/* header files */
#include <stdio.h>
#include <stdlib.h>

/* main */
int main(void) {
    int i;
    double *ptr;
    int nmemb = 3;

    /* double サイズ 3 個分の領域を確保 */
    if ((ptr=(double *)calloc(nmemb,sizeof(double)))==NULL){
        fprintf(stderr, "メモリ領域を確保に失敗しました.\n");
        return EXIT_FAILURE;
    }

    /* 適当に値を入力 */
    ptr[0] = 1950;

    /* メモリ領域の内容を表示する */
    for ( i = 0; i < nmemb; i++ ) {
        printf("  %.1f", ptr[i]);
    }
    printf("\n");

    /* メモリ領域の解放 */
    free(ptr);

    return EXIT_SUCCESS;
}

実行例

サンプルプログラムの実行結果は以下のようになります.

  1950.0  0.0  0.0