
- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
C 庫 - calloc() 函式
C 的stdlib 庫calloc() 函式用於分配請求的記憶體並返回指向它的指標。它為物件陣列預留一塊記憶體,並將分配的儲存區中的所有位元組初始化為零。
如果我們嘗試在沒有初始化的情況下讀取已分配記憶體的值,我們將得到“零”,因為 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
廣告