Write a program to implement dynamic memory reallocation using realloc() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int index=0, i=0,n,*marks;
int ans;
marks = (int*)malloc(sizeof(int));
if (marks == NULL)
{
printf("Memory cannot be allocated");
}
else {
printf("Memory has been successfully allocated by ""using malloc\n");
printf("\nMarks = %pc\n",marks);
do {
printf("\nEnter Marks ");
scanf("%d", &marks[index]);
printf("Would you like to add more(1/0):");
scanf("%d", &ans);
if (ans == 1) {
index++;
marks = (int*)realloc(marks,(index + 1)* sizeof(int));
if (marks == NULL)
{
printf("Memory cannot be allocated");
}
else {
printf("Memory has been successfully ""reallocated using realloc:\n");
printf("\nBase address of marks are:%pc",marks);
}
}
} while (ans == 1);
for (i = 0; i <= index; i++) {
printf("Marks of students %d are: %d\n",i,marks[i]);
}
free(marks);
}
return 0;
}
Output
Memory has been successfully allocated by using malloc
Marks = 00DA2E78c
Enter Marks 90
Would you like to add more(1/0): 1
Memory has been successfully reallocated using realloc:
Base address of marks are:00DA2E78c
Enter Marks 91
Would you like to add more(1/0): 1
Memory has been successfully reallocated using realloc:
Base address of marks are:00DA2E78c
Enter Marks 98
Would you like to add more(1/0): 1
Memory has been successfully reallocated using realloc:
Base address of marks are:00DA2E78c
Enter Marks 95
Would you like to add more(1/0): 0
Marks of students 0 are: 90
Marks of students 1 are: 91
Marks of students 2 are: 98
Marks of students 3 are: 95