Data Structure Algorithms with C Language
About Lesson

calloc (Clear Allocation)

used to allocate multiple blocks of memory dynamically with specified size

 

Differences between malloc and calloc

  • malloc can be called with single argument while calloc is called with two arguments.
  • calloc also initialises the memory while allocating.

 

syntax:

void *calloc(n,size);

where n – number of blocks

size- size of each block

 

Eg: int *ptr=(int *)calloc(10,sizeof(int));

 

//Example Program

#include<stdio.h>

 

void main()

{

    int n,i;

    printf(“Enter number of integer variables you want:”);

    scanf(“%d”,&n);

 

    int *ptr=(int *)calloc(n,sizeof(int));

 

    for(i=0;i<n;i++)

    {

        printf(“Enter value %d: “,i+1);

        scanf(“%d”,ptr+i);

    }

 

    printf(“nnYour Elements are:n”);

    for(i=0;i<n;i++)

    {

        printf(“%d “,*(ptr+i));

    }

}

You cannot copy content of this page