Dynamic Memory Allocation in C using Calloc

Dynamic memory allocation using calloc in C :

 On this page we will discuss about dynamic memory allocation using calloc function in C programming language. calloc( )  is used  contiguous block of memory at run time   those memory block are initialized to zero. calloc() return the base address of allocated memory on successful allocation. calloc function is similar as malloc function.
dynamic memory allocation using calloc

Dynamic memory allocation using calloc function

The calloc function  is used to allocate multiple memory block of same size in contiguous manner at run time .That is why calloc( ) is also know as contiguous allocation.The only difference between calloc and malloc is of intialization.In calloc the each memory block when allocated  is initialized with zero.
The calloc ( ) is predefined function which comes under stdlib.h .It returns a NULL pointer in case of failure of memory allocation. Calloc function has two parameter first is number of blocks and second is size of each block.
On successful allocation of memory a pointer is returned containing the base address of allocated memory. Otherwise in case of failure of memory allocation NULL pointer is returned.

Syntax: ptr = (cast_type *) calloc (a, s);
(where ‘a’ is number of blocks and s is size of each memory block.)

Example:

dynamic allocation using calloc function

Implementation of dynamic memory allocation using calloc :

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

int main ()
{

  int *ptr;			//pt to hold base address of memory block allocated
  int a, j;


  a = 5;			//number of elements in block
  printf ("Enter number of elements: %d\n", a);

  ptr = (int *) calloc (a, sizeof (int));	//syntax of calloc
  if (ptr == NULL)
    {
      printf ("Memory not allocated.\n");
      return 0;
    }

  printf ("Memory allocated successful.\n");

  for (j = 0; j < a; ++j)
    {
      ptr[j] = j + 1;
    }

  printf ("The elements of the array are: ");
  for (j = 0; j < a; ++j)
    {
      printf ("%d, ", ptr[j]);
    }


  return 0;
}

Output:

Enter number of elements: 5
Memory allocated successful.
The elements of the array are: 1, 2, 3, 4, 5

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription