C program for using malloc,calloc,realloc and free function.

#include <stdio.h> 
#include <stdlib.h>
 int main() 
{
    int* p; 
    int n, i;
    n=5; 
    printf("Enter number of elements: %d\n", n);
    p=(int*)calloc(n, sizeof(int));
    if (p==NULL) 
    { 
      printf("\n Memory not allocated"); 
      exit(0); 
    } 
   else 
   { 
    printf("\n ***Memory successfully allocated using calloc***"); 
    for(i=1;i<=n;++i) 
    { 
      p[i]=i+i; 
   } 
    printf("\n •••The elements of the array are•••"); 
    for(i=1;i<=n;++i) 
    { 
    printf("\n \t %d",p[i]); 
    } 
    n=10; 
    printf("\n Enter the new size of the array: %d\n", n); 
    p= realloc(p,n * sizeof(int));
    printf("\n ***Memory successfully re-allocated using realloc***"); 
    for(i=6;i<=n;++i) 
    { 
       p[i]=i+i; 
    }
    printf("\n •••The elements of the array are•••"); 
    for(i=6;i<=n;++i) 
    { 
    printf("\n \t %d",p[i]); 
    } 
    free(p); 
  } 
   return 0;
}


***Input && Output***


   

Post a Comment

0 Comments