C Program to Find Largest Number Using Dynamic Memory Allocation
C program to Find Largest Number
On this page we will write C program to find the largest number using dynamic memory allocation . Dynamic memory allocation means memory allocation at run.It help us to avoid wastage of storage . Here on this page we will use calloc( ) and malloc( ) to find the largest number.
Largest Number Using Dynamic Memory Allocation
The memory which is allocated at run time is called dynamic memory allocation.Heap is the segment of memory where dynamic memory allocation takes place.Heap is an area of memory where memory is allocated or de- allocated without any order or randomly.
Built in functions for dynamic memory allocation in C
- malloc( )
- calloc( )
- realloc( )
- free( )
Program 1:
#include<stdio.h> #include<conio.h> int main () { int i, n = 4; int *ele; ele = (int *) calloc (n, sizeof (int)); if (ele == NULL) { printf ("No memory allocated"); exit (0); } *(ele + 0) = 45; *(ele + 1) = 67; *(ele + 2) = 68; *(ele + 3) = 53; for (i = 0; i < n; ++i) { printf ("Number%d: %d\n", i + 1, ele[i]); } for (int i = 1; i < n; ++i) { if (*ele < *(ele + i)) { *ele = *(ele + i); } } printf ("Largest number = %d", *ele); free (ele); return 0; }
Output :
Number1: 45 Number2: 67 Number3: 68 Number4: 53 Largest number = 68
Program 2:(Using malloc())
#include<stdio.h> #include<conio.h> int main () { int i, n = 3; int *ele; ele = (int *) malloc (n * sizeof (int)); if (ele == NULL) { printf ("No memory allocated"); exit (0); } *(ele + 0) = 64; *(ele + 1) = 98; *(ele + 2) = 79; for (i = 0; i < n; ++i) { printf ("Number%d: %d\n", i + 1, ele[i]); } for (int i = 1; i < n; ++i) { if (*ele < *(ele + i)) { *ele = *(ele + i); } } printf ("Largest number = %d", *ele); free (ele); return 0; }
Output :
Number1: 64 Number2: 98 Number3: 79 Largest number = 98
There are few problems that dynamic memory allocation overcomes that we faced in static memory allocation like:
- If you are allocating memory for an array during compile time then you have to fix the size at the time of declaration. Size is fixed and user cannot increase or decrease the size of the array at run time.
- If the values stored by the user in the array at run time is less than the size specified then there will be wastage of memory.
- If the values stored by the user in the array at run time is more than the size specified then the program may crash or misbehave.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment