Example program on Dynamic memory allocation in C language



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

 Live Demo

#include<stdio.h> int main(){    int *p,n,i,max=-32768,min=32767;    printf("
enter size:");    scanf("%d",&n);    p=(int*)malloc(n*sizeof(int)); //dynamic memory allocation    printf("
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("
maximum=%d
minimum=%d",max,min);    free(p); }

Output

enter size: enter elements: maximum=-32768 minimum=32767
Updated on: 2021-03-09T08:25:51+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements