Problem
Find out the maximum and minimum from an array using dynamic memory allocation in C.
Solution
The Dynamic memory allocation enables the C programmers to allocate memory at runtime.
The different functions that we used to allocate memory dynamically at run time are −
The malloc () − allocates a block of memory in bytes at runtime.
The calloc () − allocates continuous blocks of memory at runtime.
The realloc () − used to reduce (or) extend the allocated memory.
The free () − deallocates previously allocated memory space.
Finding maximum and minimum number in an array using dynamic memory allocation
The logic for finding maximum element in an array −
First allocate memory to the array
p=(int*)malloc(n*sizeof(int)); //dynamic memory allocation
for(i=0;i<n;i++){
scanf("%d",p+i);
if(*(p+i)>max) //finding max element
max=*(p+i);
}The logic for finding minimum element in an array −
for(i=0;i<n;i++){
scanf("%d",p+i);
if(*(p+i)<min) //finding min element
min=*(p+i);
}Example
#include<stdio.h>
int main(){
int *p,n,i,max=-32768,min=32767;
printf("\n enter size:");
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int)); //dynamic memory allocation
printf("\n enter elements:");
for(i=0;i<n;i++){
scanf("%d",p+i);
if(*(p+i)>max) //finding max element
max=*(p+i);
if(*(p+i)<min) //finding min element
min=*(p+i);
}
printf("\n maximum=%d\n minimum=%d",max,min);
free(p);
}Output
enter size: enter elements: maximum=-32768 minimum=32767