DYNAMIC MEMORY ALLOCATION
Note : - In C language Dynamic Memory allocation is perform in heap area of memory.
* realloc ( )
- This function is used to reallocate space in memory which is allocated by malloc & calloc.
like malloc() or calloc( ) realloc( ) function returns / void pointer.
The prototype of realloc( ) function is specified in stdlib.h
Syntax :- pointer-variable = (cast type*)realloc(pointer-variable,size-in-byte);
Example :- int *p;
p=(int*)malloc(5*sizeof(int));
p=(int*)realloc(p,25*sizeof(int));
#include<stdio.h>
Eg: Program for Array using calloc( ) & realloc ( )
- #include<stdlib.h>
#include<conio.h>
main()
{
int *array, size, size2, i;
printf ("Enter the size of an array = ");
scanf ("%d",&size);
array =(int*)malloc(size*sizeof(int));
printf ("Enter %d elements :-\n",size);
for (i=0;i<size;i++)
{
scanf ("%d",array+i);
}
printf ("Inital stored elemnts in array :-\n");
for (i=0;i<size;i++)
{
printf ("%d\n",*(array+i));
}
printf ("How much memory you want to reallocate for this array = ");
scanf ("%d",&size2);
array =(int*)realloc(array,size+size2*sizeof(int));
printf ("Enter %d elements :-\n",size2);
for (i=size;i<size+size2;i++)
{
scanf ("%d",array+i);
}
printf ("All %d elemnts after reallocation are :-\n",(size+size2));
for (i=0;i<(size+size2);i++)
{
printf ("%d\n",*(array+i));
}
free(array);
}
0 Comments
Thank You ! For your love