realloc()
Function (Re Allocation Function)
Suppose
previously allocated dynamic memory is not sufficient (or) memory is much
larger than the requirement, in both cases some memory changes are
required. Memory changes can be done by
using a library function called realloc() function.
realloc() function provides
the altering the size of the memory allocation and the process is called
reallocation of memory. The general form
of realloc() function is:
Syntax: ptrvariable =
(casttype*)realloc(ptrvariable,newsize);
Where,
ptrvariable is a pointer variable of type casttype.
Here,
This function allocates a new memory space of the
specified newsize and returns a pointer variable that represent first byte of
the new memory block. The newsize may be
larger or smaller than the previous size.
Note:
I.
The new
memory block may or may not be begin at the same place as the old one. In case, it is not able to find additional
space in the same region, it will create the same in an entirely new region and
moves the contents of the old block into the new block.
II.
If the
function is unsuccessful to allocate the memory space, it returns a NULL
pointer and the original block is lost.
/*
EXAMPLE PROGRAM FOR REALLOC() FUNCTION */
main()
{
int *p,i,n;
clrscr();
printf("\nEnter how many
numbers:");
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int));
p=(int*)realloc(p,(n+2)*sizeof(int));
printf("\nEnter %d
Elements:",n+2);
for(i=0;i<n+2;i++)
scanf("%d",p+i);
printf("\nArray Elements
Are:");
for(i=0;i<n+2;i++)
printf(" %d",*(p+i));
}
No comments:
Post a Comment