Dynamic memory allocation


The process of allocating memory to the variables during execution of the program or at the run time is known as dynamic memory allocation,c language has four library routines which allow this function.For example: int arr[100] When this statement is executed,consecutive space for 100 integers is allocated.It is not uncommon that we may be using only 10% or 20% of the allocated space thereby wasting rest of the space.To overcome this problem and to utilize the memory efficiently c language provides a mechanism of dynamically allocating memory so that only the amount of memory that is actually required is reserved.We reserved space only at the run time for the variables that are actually required.C provides four library routines to automatically allocate memory at the run time.malloc()-Allocates memory and returns a pointer to the first byte of allocated space.calloc-Allocates space for an array elements and initializes them to zero.like malloc(),calloc()also returns a pointer to the memory.free()-Free previously allocated memoryrealloc-Alerts the size of previously allocated memory. 

Write a program to read and display values of an integer array.Allocate space dynamically for the array

#include<stdio.h>
#include<coino.h>
#include<stdlib.h>
void main()
{
int i,n;
int *arr;
clrscr();
printf("\n Enter the number of elements");
scanf("%d",&n);
arr=(int*)malloc(n*sizeof(int));
if(arr=null)
{
printf("\n memory allocation failed");
exit(0);
}
for(i=0;i<n;i++)
{
printf("\n Enter the values %d of the array:",i);
scanf("%d",&arr[i]);
}
printf("\n the array contains\n");
for(i=0;i<n;i++)
printf("%d",arr[i]);
getch();
}

Comments