C calloc()

The calloc() function is defined in the stdlib.h header file. It helps to allocate the specified memory and returns a pointer to it. The calloc() function can set allocated memory to zero.


void *calloc(size_t nitems, size_t size); #where nitems should be a integer

 

calloc() Parameters: 

The calloc() function takes two parameters. This function helps to allocate multiple memory blocks having the same size and contiguous allocation.

Parameter Description Required / Optional
nitems  the number of elements to be allocated Required
size the size of elements Required

calloc() Return Value

The return value of calloc() function is a pointer to the allocated memory.

Input Return Value
success pointer to memory
fails NULL

Examples of calloc() 

Example 1: Working of calloc() function in C?


#include <stdio.h>
#include <stdlib.h>

int main()
{
   int k, num;
   int *p;

   printf("count of entered elements :");
   scanf("%d",&num);

   p = (int*)calloc(num, sizeof(int));
   printf("Enter %d numbers:\n",num);
   for( k=0 ; k < num ; k++ ) {
      scanf("%d",&p[k]);
   }

   printf("Entered elements are: ");
   for( k=0 ; k < num ; k++ ) {
      printf("%d ",p[k]);
   }
   free( p );
   
   return(0);
}

Output:


count of entered elements:3
Enter 3 numbers:
13
15
20
Entered elements are: 13 15 20

Example 2: How calloc() works in C?


#include <stdio.h>
#include <stdlib.h>

int main (){
  int k, * pt, t = 0;
        pt = calloc(10, sizeof(int));
        if (pt == NULL) {
            printf("Error! memory not allocated.");
            exit(0);
        }
        printf("Sequence sum of the first 10 terms \ n ");
        for (k = 0; k < 10; ++k) { * (pt + k) = k;
            sum += * (pt + k);
        }
        printf("Sum = %d", t);
        free(pt);
        return 0;
}

Output:


Sequence sum of the first 10 terms
Sum = 45