calloc function

Using calloc function, we can create memory dynamically at runtime.

calloc is declared in <stdlib.h> i.e. standard library header file.

To use calloc function in our program, we have to include <stdlib.h> header file.




syntax of calloc

calloc(number of elements, size of the element);

Example

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

calloc will take two arguments.

where,

ptr is a pointer. It can be any type.

calloc - used to create dynamic memory

n - number of elements

size- size of the elements




How does calloc work?

It will return the base address of an allocated memory to the pointer variable, on success.

If calloc unable to create the dynamic memory, it will return NULL.

So, it is mandatory to check the pointer before using it.

Example

//allocating memory for 5 integers using calloc
int *ptr = calloc(5,sizeof(int));

Pictorial Explanation

calloc in c

calloc will create 20 ( 5 * 4 ) bytes of memory and return the base address to pointer variable ptr on success.




Initialization

calloc will initialize the memory to zero.

So, the allocated memory area will be set to 0.



Animated Tutorial




Let's create a dynamic memory using calloc

Example

/*
 *Dynamic memory creation using calloc
 *Language: C
 */

#include<stdio.h>
//To use calloc function in our program
#include<stdlib.h>

int main()
{
    int *ptr;

    //allocating memory for 1 integer
    ptr = calloc(1,sizeof(int));

    if(ptr != NULL)
           printf("Memory created successfully\n");

    return 0;
}




Let's get size input from the user and allocate the dynamic memory using calloc.

Example

/*
 *Dynamic memory creation using calloc
 *Language: C
 */

#include<stdio.h>
//To use calloc function in our program
#include<stdlib.h>

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

    scanf("%d",&n);

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

    if(ptr != NULL)
    {
           //let's get input from user and print it
           printf("Enter numbers\n");

           for(i = 0; i < n; i++)
                 scanf("%d",ptr+i);

           //printing values
           printf("The numbers are\n");

           for(i = 0; i < n; i++)
                 printf("%d\n",*(ptr+i)); // *(ptr+i) is as same as ptr[i] 

    }

    return 0;
}