Sunday 22 July 2012

UNDERSTANDING THE USE OF realloc() FUNCTION

UNDERSTANDING THE USE OF realloc() FUNCTION
realloc():
Declaration:
void *realloc(void *ptr, size_t newsize);
It is used for reallocation of memory. If we want to increase or decrease the memory that have already been allocated by malloc() or calloc().

The memory size is altered without any loss of old data.

It takes two arguments:
1)The first argument is the pointer to the memory block that was already allocated by malloc() and calloc().
2)The second argument is the new size of the block.


Let us understand it with the help of program:
* Program to understand the use of realloc()*/

#include<stdio.h>
#include<alloc.h>

int main()
{

int *ptr,i;


//Allocating memory using malloc
ptr=(int *) malloc(5*sizeof(int));



printf(" \n----------Using malloc:-------------\n");

//Check if memory is available

if(ptr==NULL)
{
printf("Out of memory." );
return 0;
}

//Accept the integers with size using malloc
printf("Enter 5 integers:\n");
for(i=0;i<5;i++)
 {
scanf("%d",ptr+i);
 }
 printf("The integers entered are:\n");
for(i=0;i<5;i++)
 {
printf("%d\t",*(ptr+i));
}
printf(" \n\n\n----------Using realloc:-------------\n");
 //Allocating size for 4 more integers using realloc
 ptr=(int *) realloc(ptr,9*sizeof(int)); //Check if memory is available
if(ptr==NULL)
 {
 printf("Out of memory." );
 return 0;
}
 //Accept the new data
printf("Enter 4 more integers:\n");
for(i=5;i<9;i++)
{ scanf("%d",ptr+i);
} //display the integers with size using calloc
 printf("The integers entered are:\n");
 for(i=0;i<9;i++)
 {
printf("%d\t",*(ptr+i));
} return 0;
 }
Share This
Previous Post
Next Post

FYJC XI standard online admisson Process and declaraton of Merit list . Cut off List For prevous year also . 10 Th Results onlne declaraton Maharashtra Region .

0 comments: