- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements