Write a C Program to understand the use of realloc() function. Here’s a Simple Program to understand the use of realloc( ) function in C Programming Language.
If the previously allocated memory is insufficient or more than required, you can change the previously allocated memory size using realloc().
Description
The C library function void *realloc(void *ptr, size_t size) attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc.
Syntax of realloc() : :
ptr = realloc(ptr, size);
Parameters
ptr — This is the pointer to a memory block previously allocated with malloc, calloc or realloc to be reallocated. If this is NULL, a new block is allocated and a pointer to it is returned by the function.
size — This is the new size for the memory block, in bytes. If it is 0 and ptr points to an existing block of memory, the memory block pointed by ptr is deallocated and a NULL pointer is returned.
Return Value
This function returns a pointer to the newly allocated memory, or NULL if the request fails.
Below is the source code for C Program to understand the use of realloc() function which is successfully compiled and run on Windows System to produce desired output as shown below :
SOURCE CODE : :
/* Program to understand the use of realloc() function*/
#include<stdio.h>
#include<stdlib.h>
int main( )
{
int i, *ptr;
ptr = (int *)malloc(5 *sizeof(int));
if(ptr == NULL)
{
printf("Memory not available\n");
exit(1);
}
printf("Enter 5 integers : ");
for(i=0; i<5; i++)
scanf("%d", ptr+i);
/*Allocate memory for 4 more integers*/
ptr = (int *)realloc(ptr, 9*sizeof(int));
if(ptr == NULL)
{
printf("Memory not available\n");
exit(1);
}
printf("Enter 4 more integers : ");
for(i=5; i<9; i++)
scanf("%d", ptr+i);
for(i=0; i<9; i++)
printf("%d ", *(ptr+i));
}
OUTPUT ::
//OUTPUT ::
Enter 5 integers : 6
3
4
5
9
Enter 4 more integers : 7
0
1
1
6 3 4 5 9 7 0 1 1
C realloc()
If the previously allocated memory is insufficient or more than required, you can change the previously allocated memory size using realloc().
Description
The C library function void *realloc(void *ptr, size_t size) attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc.
Syntax of realloc() : :
Parameters
Return Value
This function returns a pointer to the newly allocated memory, or NULL if the request fails.
Below is the source code for C Program to understand the use of realloc() function which is successfully compiled and run on Windows System to produce desired output as shown below :
SOURCE CODE : :
OUTPUT ::
need an explanation for this answer? contact us directly to get an explanation for this answer