written 5.7 years ago by | • modified 5.7 years ago |
Dynamic memory allocation:
Dynamic Memory Allocation refers to managing system memory at runtime.
Dynamic memory management in C programming language is performed via a group four functions namely malloc(),calloc().
These four dynamic memory allocation function of the C programming language are defined in the C standard library header file<stdlib.h>. Dynamic memory allocation uses the heap space of the system memory.
malloc()
malloc() is used to allocate a block of memory on the heap.
Specifically,malloc() allocates the user a specified number of bytes but does not initialize.
Once allocated, the program accesses this block of memory via a pointer that malloc() returns.
The default pointer returned by malloc() is of the type void but can be cast into a pointer of any datatype.
However, if the space is insufficient for the amount of memory requested by malloc().
Then the allocation fails and a NULL pointer is returned.
The function takes a single argument, which is the size of the memory chunk to be allocated.
program to find maimum and minimum element from the array
#include<stdio.h>
#include<conio.h>
#define MAX_SIZE 100
void main()
{
int arr[MAX_SIZE];
int i, max, min, size;
clrscr();
printf("Enter size of the array: ");
scanf("%d", &size);
printf("Enter elements in the array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
max = arr[0];
min = arr[0];
for(i=1; i<size; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
if(arr[i] < min)
{
min = arr[i];
}
}
printf("Maximum element = %d\n", max);
printf("Minimum element = %d", min);
getch();
}
Output:
Enter size of the array: 10
Enter elements in the array:
6
4
3
8
9
12
65
87
54
24
Maximum element=87
Minimum element=3