Calloc

The name calloc stands for "contiguous allocation". 
The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero. 
Another difference between malloc and calloc is that , malloc allocates some amount of memory , it does not initialize the byte with any value, so if you do not fill any values in the addresses allocated by malloc,the malloc will assign garbagevalues in the block of memory, 
but if the memory is allocated by calloc, the calloc sets all byte position to value zero, so it initializes the memory that it allocates to zero. 
Calloc also returns a void pointer same as malloc.

Syntax :

void * calloc (size_t n, size_t size);

there are two arguments, 
1. size_t n : the number of elements of particular datatype 
2. size_t size : the size of the datatype.

Example :

ptr=(cast-type*)calloc(n,element-size);

This statement will allocate contiguous space in memory for an array of n elements


ptr=(float*)calloc(25,sizeof(float));

This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes.

Example :

#include <stdio.h>
#include <stdlib.h>
void main()
{
    int n,i,*ptr,sum=0;

    printf("Enter number of elements: ");
    scanf("%d",&n);

    ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc

    if(ptr==NULL)
    {
        printf("Requested size of memory is unavailable ");
        exit(0);
    }

    printf("Enter elements of array: ");
    for(i=0;i<n;++i)
    {
        scanf("%d",ptr+i);
        sum+=*(ptr+i);
    }
    printf("Sum=%d",sum);
}

Output :
Enter number of elements: 4
Enter elements of array:
5
5
5
5
Sum=20

Post a Comment

0 Comments