calloc() Function in C Library with Program EXAMPLE

What is calloc in C?

The calloc() in C is a function used to allocate multiple blocks of memory having the same size. It is a dynamic memory allocation function that allocates the memory space to complex data structures such as arrays and structures and returns a void pointer to the memory. Calloc stands for contiguous allocation.

Malloc function is used to allocate a single block of memory space while the calloc function in C is used to allocate multiple blocks of memory space. Each block allocated by the calloc in C programming is of the same size.

calloc() Syntax:

ptr = (cast_type *) calloc (n, size);

Whenever there is an error allocating memory space such as the shortage of memory, then a null pointer is returned as shown in the below calloc example.

How to use calloc

The below calloc program in C calculates the sum of an arithmetic sequence.

#include <stdio.h>
    int main() {
        int i, * ptr, sum = 0;
        ptr = calloc(10, sizeof(int));
        if (ptr == NULL) {
            printf("Error! memory not allocated.");
            exit(0);
        }
        printf("Building and calculating the sequence sum of the first 10 terms \ n ");
        for (i = 0; i < 10; ++i) { * (ptr + i) = i;
            sum += * (ptr + i);
        }
        printf("Sum = %d", sum);
        free(ptr);
        return 0;
    }

Result of the calloc in C example:

 
Building and calculating the sequence sum of the first 10 terms
Sum = 45

 

YOU MIGHT LIKE: