C 庫 - calloc() 函式



C 的stdlibcalloc() 函式用於分配請求的記憶體並返回指向它的指標。它為物件陣列預留一塊記憶體,並將分配的儲存區中的所有位元組初始化為零。

如果我們嘗試在沒有初始化的情況下讀取已分配記憶體的值,我們將得到“零”,因為 calloc() 已經將其初始化為 0。

語法

以下是 calloc() 函式的 C 庫語法 -

void *calloc(size_t nitems, size_t size)

引數

此函式接受以下引數 -

  • nitems - 它表示要分配的元素數量。

  • size - 它表示每個元素的大小。

返回值

以下是返回值 -

  • 返回指向已分配記憶體的指標,所有位元組都初始化為零。

  • 如果分配失敗,則返回空指標。

示例 1

在此示例中,我們建立了一個基本的 C 程式來演示如何使用 calloc() 函式。

#include <stdio.h>
#include <stdlib.h>
int main() {
   int n = 5;
   int *array;
   
   // use calloc function to allocate the memory
   array = (int*)calloc(n, sizeof(int));
   
   if (array == NULL) {
      fprintf(stderr, "Memory allocation failed!\n");
      return 1;
   }
   
   //Display the array value
   printf("Array elements after calloc: ");
   for (int i = 0; i < n; i++) {
      printf("%d ", array[i]);
   }
   printf("\n");
   
   //free the allocated memory
   free(array);
   return 0;
}

輸出

以下是輸出 -

Array elements after calloc: 0 0 0 0 0 

示例 2

讓我們再建立一個 C 示例,我們使用 calloc() 函式為數字分配記憶體。

#include <stdio.h>
#include <stdlib.h>
int main() {	
   long *number;   
   //initialize number with null
   number = NULL;
   if( number != NULL ) {
      printf( "Allocated 10 long integers.\n" );
   }      
   else {
      printf( "Can't allocate memory.\n" );
   }
   
   //allocating memory of a number
   number = (long *)calloc( 10, sizeof( long ) );
   if( number != NULL ) {
      printf( "Allocated 10 long integers.\n" );
   }      
   else {
      printf( "\nCan't allocate memory.\n" );
   }   
   //free the allocated memory   
   free( number );
}

輸出

以下是輸出 -

Can't allocate memory.
Allocated 10 long integers.

示例 3

以下是使用 calloc() 函式為指標分配記憶體的 C 程式,大小為零。

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

int main() {
   int *pointer = (int *)calloc(0, 0);
   if (pointer == NULL) {
      printf("Null pointer \n");
   } else {
      printf("Address = %p", (void*)pointer);
   }
   free(pointer);
   return 0;
}

輸出

以下是輸出 -

Address = 0x55c5f4ae02a0
廣告