Easy Tutorial
❮ C Function Strtod C Exercise Example46 ❯

C Library Function - calloc()

C Standard Library - <stdlib.h>

Description

The C library function void *calloc(sizet nitems, sizet size) allocates the required memory space and returns a pointer to it. The difference between malloc and calloc is that malloc does not set the memory to zero, while calloc sets the allocated memory to zero.

Declaration

Below is the declaration for the calloc() function.

void *calloc(size_t nitems, size_t size)

Parameters

Return Value

The function returns a pointer to the allocated memory. If the request fails, it returns NULL.

Example

The following example demonstrates the use of the calloc() function.

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

int main()
{
   int i, n;
   int *a;

   printf("Number of elements to be entered:");
   scanf("%d",&n);

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

   printf("The numbers entered are: ");
   for( i=0 ; i < n ; i++ ) {
      printf("%d ",a[i]);
   }
   free (a);  // Free the memory
   return(0);
}

Let's compile and run the above program, which will produce the following result:

Number of elements to be entered: 3
Enter 3 numbers:
22
55
14
The numbers entered are: 22 55 14

C Standard Library - <stdlib.h>

❮ C Function Strtod C Exercise Example46 ❯