Showing posts with label What is use of calloc() function. Show all posts
Showing posts with label What is use of calloc() function. Show all posts

What is Calloc() function in C Programming Language?


What is Calloc() function in C Programming Language?


A calloc() function allocates space for an array of elements of a certain size and initializes the memory to zero. 

  • void  *calloc(size_t num, size_t size);
Here num is number of objects to allocate and size is the size of each objects. If the allocation is successful then function returns a Pointer to the first byte and if allocation fails then the function returns NULL. 

Examples:

  • #include<stdio.h>
  • #include<stdlib.h>
  • void main()
  • {
  •           unsigned a;
  •           int *ptr;
  •           printf(“Enter the number to allocate:-”);
  •           scanf("%d", &a);
  •           ptr= (int*) calloc(a, sizeof(int));
  •           if(ptr!=NULL)
  •           {
  •                      puts("Memory allocation successful");
  •            }
  •           else
  •           {
  •                     puts("Memory allocation failed");
  •           }
  •           return(0);
  • }


Output:-
  • Enter the number to allocate:- 200
  • Memory allocation successful
  • Enter the number to allocate:- 111111111111
  • Memory allocation failed