C programming stdlib.h function - void *calloc(size_t nitems, size_t size)
The calloc
function is a memory allocation function in the C standard library that is used to allocate memory for an array of nitems
elements, each of which has a size of size
bytes. The syntax of the calloc
function is as follows:
void *calloc(size_t nitems, size_t size);
The nitems
argument is the number of elements to be allocated, and size
is the size of each element. The function returns a pointer to the allocated memory block if the allocation is successful, and NULL
if the allocation fails.
The calloc
function initializes all the bytes in the allocated memory block to zero. This is different from the malloc
function, which does not initialize the allocated memory block.
Here is an example that demonstrates how to use the calloc
function to allocate memory for an array:
#include <stdio.h> #include <stdlib.h> int main(void) { int n = 10; int *array = (int *)calloc(n, sizeof(int)); if (array == NULL) { printf("Memory allocation failed\n"); return 1; } for (int i = 0; i < n; i++) { printf("%d ", array[i]); } printf("\n"); free(array); return 0; }
In this example, the calloc
function is used to allocate memory for an array of 10 int
elements. The size of each element is sizeof(int)
. The program then uses a for
loop to print out the elements of the array. Since the calloc
function initializes all the bytes in the allocated memory block to zero, the output of the program is:
0 0 0 0 0 0 0 0 0 0
Note that the calloc
function returns NULL
if the allocation fails. It is a good practice to check the value returned by the calloc
function to make sure that the allocation was successful before using the allocated memory block. Also, just like with the malloc
function, you must call the free
function to release the allocated memory block when you are done using it.