What is Dynamic Memory Allocation? Allocation of memory at runtime is called dynamic memory allocation. There are four functions in c to allocate memory dynamically.
malloc(): Syntax: Ptr = (datatype*)malloc(size); Example: Int * ptr ; ptr =(int*)malloc(20); (or) ptr =(int*)malloc(5* sizeof (int)); Example Program: int main(){ int * ptr,n ; printf (“Enter the value of n=“); scanf (“% d”,&n ); ptr =(int*)malloc(n* sizeof (int)); printf (“enter numbers=“); for(int i =0; i <n; ++ i ){ scanf (“%d”, p+i ); } free( ptr ); return 0; }
calloc (): Syntax: Ptr = (datatype*) calloc ( n,size ); Example: Int * ptr ; ptr =(int*) calloc (10,2); (or) ptr =(int*) calloc (10,sizeof(int)); Example Program: int main(){ int * ptr,n ; printf (“Enter the value of n=“); scanf (“% d”,&n ); ptr =(int*) calloc ( n,sizeof (int)); printf (“enter numbers=“); for(int i =0; i <n; ++ i ){ scanf (“%d”, p+i ); } free( ptr ); return 0; }
realloc (): Syntax: Ptr = (datatype*) realloc ( ptr,newsize ); Example: Int * ptr ; ptr =(int*)malloc(n* sizeof (int)); ptr =(int*) realloc (ptr,20); Example Program: int main(){ int * ptr,n ; printf (“Enter the value of n=“); scanf (“% d”,&n ); ptr =(int*)malloc(n* sizeof (int)); ptr =(int*) realloc (ptr,20); printf (“enter numbers=“); for(int i =0; i <n; ++ i ){ scanf (“%d”, p+i ); } free( ptr ); return 0; }
free(): Syntax: free( ptr ); Example: Int * ptr ; ptr =(int*)malloc(n* sizeof (int)); free( ptr ); Example Program: int main(){ int * ptr,n ; printf (“Enter the value of n=“); scanf (“% d”,&n ); ptr =(int*)malloc(n* sizeof (int)); printf (“enter numbers=“); for(int i =0; i <n; ++ i ){ scanf (“%d”, p+i ); } free( ptr ); return 0; }
Programs: Q) WAP to allocate 3 numbers in an array dynamically and find the sum of the 3 numbers allocated. #include<stdio.h> #include<stdlib.h> int main(){ int n,i ,* ptr,sum =0; printf ("Enter number of elements: "); scanf ("% d",&n ); ptr =( int *)malloc(n* sizeof ( int )); //memory allocated using malloc if ( ptr ==NULL) { printf ("Sorry! unable to allocate memory"); exit(0); } printf ("Enter elements of array: "); for ( i =0;i<n;++ i ) { scanf ("%d", ptr+i ); sum+=*( ptr+i ); } printf ("Sum=% d",sum ); free( ptr ); return 0; }
#include<stdio.h> #include<stdlib.h> int main(){ int n,i ,* ptr,sum =0; printf ("Enter number of elements: "); scanf ("% d",&n ); ptr =( int *)malloc(n* sizeof ( int )); //memory allocated using malloc if ( ptr ==NULL) { printf ("Sorry! unable to allocate memory"); exit(0); } printf ("Enter elements of array: "); for ( i =0;i<n;++ i ) { scanf ("%d", ptr+i ); sum+=*( ptr+i ); } printf ("Sum=% d",sum ); free( ptr ); return 0; }
By Mrinank Kavuri Akhil Agastya Raman Pushpender Ramesh