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);
  • The above statement example of calloc in C is used to allocate n memory blocks of the same size.
  • After the memory space is allocated, then all the bytes are initialized to zero.
  • The pointer which is currently at the first byte of the allocated memory space is returned.

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

Post a Comment

0 Comments