calloc() function in c – calloc C Library Function

calloc() function in c: The function calloc allocates a continuous block of memory for an array of num elements, where size of each element is size bytes. calloc also initializes the allocated memory with zero whereas malloc does not initializes the memory.

Function prototype of calloc

void *calloc(size_t num, size_t size);

size_t is an unsigned integer type.

  • num : This is the number of elements in array to be allocated.
  • size : This is the size of each elements.

Return value of calloc

This function returns a pointer to the block of memory allocated by the calloc or null pointer If the function failed to allocate the requested block of memory. The type of returned pointer is always void*, which can be casted to any type of pointer.

C program using calloc function

The following program shows the use of calloc function to dynamically allocate an array.

calloc C Library Function

#include <stdio.h>
#include <stdlib.h>
 
int main(){
    int *array, counter, n, sum=0;
     
    printf("Enter number of elements\n");
    scanf("%d", &n);
     
    /* Allocate memory to store n integers using calloc */
    array = (int*)calloc(n, sizeof(int));
    /* 
     * Take n integers as input from user and store 
     * them in array 
     */
    printf("Enter %d numbers\n", n);
    for(counter = 0; counter < n; counter++){
        scanf("%d", &array[counter]);
    }
    /* Find sum of n numbers */
    for(counter = 0; counter < n; counter++){
        sum = sum + array[counter];
    }
    printf("Sum of %d numbers : %d", n, sum);
       
    return 0;
}

Output

Enter number of elements
5
Enter 5 numbers
1 2 3 4 5
Sum of 5 numbers : 15