Skip to main content
DYNAMIC MEMORY ALLOCATION (DMA)
In programming we use some variables and to store those
variables we used memory space to allocate some space for that variable .when
we are using array we can use or allocate memory space dynamically means to
allocate contiguous memory space during the program execution .means the way to
reserve memory address at run time is called dynamic memory allocation or in
short it refers as DMA.
There are two functions used to allocate:
Malloc():used for allocation of memory space at run time
Syntax: int *ptr;
Ptr=(int*)malloc(n*sizeof(int));
·
Here ptr accepts the base address returned by
the given statement.
·
Malloc is the function used for allocation of
memory space.
·
N stands for number of elements
·
Sizeof return the size of the data type enclosed
in the bracket
Calloc():
is same as malloc() but there is a minor
difference between this will be clear after watching this example:
Syntax: int *ptr;
Ptr=(int*)malloc(n,2);
·
Here ptr accepts the base address returned by
the given statement.
·
calloc is the function used for allocation of
memory space.
·
N stands for number of elements
·
Here two arguments are passing separated with a (,)
which mean that the each element will occupy 2 bytes in memory location.
Realloc():
used to reallocate the memory space which is previously
allocated by malloc() and calloc().
Free():
in DMA the allocated varibles remain at the memory
space as soon as we will not remove it from that place so for this we are using
a function called free() to free the memory space so that it can be use for
other applications.
Some of the program will clear its meaning:
/*sample program to understand the DMA*/
#include<stdio.h>
#include<stdlib.h>
void main()
{
int n,*ptr,i;
scanf("%d",&n);
ptr=(int*)calloc(n,2);
for(i=0;i<n;i++)
{
scanf("%d",ptr+i);
}
for(i=0;i<n;i++)
{
printf("%d",*(ptr+i));
}
}
/*PROGRAM TO SUM THE VALUES OF AN ARRAY USING DMA*/
#include<stdio.h>
#include<stdlib.h>
int func(int *psize);
void main()
{
int
i,size,sum=0,avg;
int
*arr=func(&size);
for(i=0;i<size;i++)
{
scanf("%d",&arr[i]);
}
for(i=0;i<size;i++)
{
sum+=arr[i];
}
avg=sum/size;
printf("%d",avg);
}
int func(int *psize)
{
int *p;
printf("enter
size");
scanf("%d",psize);
p=(int*)calloc(*psize,2);
return(p);
}
/*PRGRAM TO FIND THE AVERAGE USING DMA*/
#include<stdio.h>
#include<stdlib.h>
int *func(int *psize);
void main()
{
int
i,size,sum=0;
float
avg;
int
*arr=func(&size);
for(i=0;i<size;i++)
{
scanf("%d",&arr[i]);
}
for(i=0;i<size;i++)
{
sum+=arr[i];
}
avg=sum/size;
printf("%f",avg);
}
int *func(int *psize)
{
int *p;
printf("enter
size");;
scanf("%d",psize);
p=(int*)malloc(*psize*(sizeof(int));
return(p);
}
Comments
Post a Comment