Examples of realoc() function
Question:
C program to take input for “n” elements by allocating the memory dynamically. Store the elements and display them, further change the size using realloc() function and store elements and display them.
Sol:
#include<stdio.h> #include<stdlib.h> int main() { int n,i,*p,n1; char ch; printf("Enter total elements "); scanf("%d",&n); p=(int*)malloc(p*sizeof(int)); /* or */ /* p=(int*)calloc(p,sizeof(int)); */ if(p==NULL) { printf("Memory allocation failed\n"); getch(); exit(1);//header file : stdlib.h } for(i=0;i<n;i++) { printf("Enter the element "); scanf("%d",(p+i)); } for(i=0;i<n;i++) { printf("%d\n",*(p+i)); } printf("Enter new size "); scanf("%d",&n1); p=(int*)realloc(p,sizeof(int)); if(p==NULL) { printf("Memory allocation failed\n"); getch(); exit(1);//header file : stdlib.h } for(i=n;i<n1;i++) { printf("Enter the element "); scanf("%d",(p+i)); } for(i=0;i<n1;i++) { printf("%d\n",*(p+i)); } free(p); return(0); }
/* Output */ Enter total elements 2 Enter the element 10 Enter the element 20 10 20 Enter new size 5 Enter the element 30 Enter the element 40 Enter the element 50 10 20 30 40 50
Question:
C program to take input for “n” elements by allocating the memory dynamically. Store the elements and display, further change the size using realloc() function and store elements and display them also display sum of all the elements.
Sol:
#include<stdio.h> #include<stdlib.h> int main() { int n,i,*p,n1,s=0; char ch; printf("Enter total elements "); scanf("%d",&n); p=(int*)malloc(p*sizeof(int)); /* or */ /* p=(int*)calloc(p,sizeof(int)); */ if(p==NULL) { printf("Memory allocation failed\n"); getch(); exit(1);//header file : stdlib.h } for(i=0;i<n;i++) { printf("Enter the element "); scanf("%d",(p+i)); } for(i=0;i<n;i++) { printf("%d\n",*(p+i)); s=s+*(p+i); } printf("Sum = %d\n",s); printf("Enter new size "); scanf("%d",&n1); p=(int*)realloc(p,sizeof(int)); if(p==NULL) { printf("Memory allocation failed\n"); getch(); exit(1);//header file : stdlib.h } for(i=n;i<n1;i++) { printf("Enter the element "); scanf("%d",(p+i)); } s=0; for(i=0;i<n1;i++) { printf("%d\n",*(p+i)); s=s+*(p+i); } printf("Sum = %d\n",s); free(p); return(0); }
/* Output */ Enter total elements 2 Enter the element 10 Enter the element 20 10 20 Sum = 30 Enter new size 5 Enter the element 30 Enter the element 40 Enter the element 50 10 20 30 40 50 Sum = 150