What is the purpose of realloc( )
Turn Mobile View Off
by Dinesh Thakur

The function realloc () is used to resize the memory allocated earlier by function malloc () to a new size given by the second parameter of the function. The function realloc(ptr,n) uses two arguments.the first argument ptr is a pointer to a block of memory for which the size is to be altered. The second argument n specifies the new size. The size may be increased or decreased.

If n is greater than the old size and if sufficient space is not available subsequent to the old region, the function realloc( ) may create a new region and all the old data are moved to the new region.

Illustrates malloc() and realloc ().

#include <stdio.h>


int main ()


  int a= 0, n, m, i, j,k =0;

  int* Array;


  printf("Enter the number of elements of Array.");

  scanf("%d", &n );

  Array= (int*) malloc( n* sizeof(int) );

  if( Array== NULL)


     printf("Error. Out of memory.\n");



  printf("Enter the %d elements of Array:", n);

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


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

      printf("Array[%d] = %d\n", j, *(Array+j));

      printf("Enter the number of elements of extended array.");

      scanf("%d", &m);

      Array= realloc(Array, m);

      if( Array== NULL)


         printf("realloc has failed.\n");



       printf("Enter values of %d additional elements of array.", m-n);

       for (k= n ; k<m; k++)

         scanf("%d", &Array[k]);

          for( a =0;a<m; a++)

          printf("Array[%d] = %d\n", a, *(Array+ a));

          return 0;


What is the purpose of realloc( )

Dinesh Thakur is a Technology Columinist and founder of Computer Notes and Technology Motivation. Turn Mobile View Off