Q23 Write a program to implement dynamic memory reallocation using realloc() function.

Admin

 

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

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.