Q:

Write a program to demonstrate the use of malloc and realloc in c

0

Write a program to demonstrate the use of malloc and realloc in c

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

#include<stdio.h>
#include<stdlib.h>
struct course
{
 char subjects[100];
 int marks;
};
int main()
{
  struct course*ptr;
  int i,n;
  printf("\nenter the records:");
  scanf("%d",&n);
ptr=(struct course*)malloc(n* sizeof(struct course));
for(i=0;i<n;++i)
{
  printf("\nenter the %d no of records:",i+1);
  printf("\nenter the subjects:");
  scanf("%s",&(ptr+i)->subjects);
  printf("\nenter the marks:");
  scanf("%d",&(ptr+i)->marks);
}
printf("\ndisplayed course record:");
for(i=0;i<n;i++)
{
printf("\nsubjects= %s",(ptr+i)->subjects);
printf("\nmarks= %d",(ptr+i)->marks);
}
printf("\n------------------------------------------------------");
printf("\nenter the new records you want to create:");
  scanf("%d",&n);
ptr=(struct course*)realloc(ptr,n* sizeof(struct course));
for(i=0;i<n;i++)
{
  printf("\nenter the %d no of records:",i+1);
 
  printf("\nenter the subjects:");
  scanf("%s",&(ptr+i)->subjects);
  printf("\nenter the marks:");
  scanf("%d",&(ptr+i)->marks);
}
printf("\ndisplayed course record:");
for(i=0;i<n;i++)
{
printf("\nsubjects=%s",(ptr+i)->subjects);
printf("\nmarks=%d",(ptr+i)->marks);
}
return 0;
}

Output:

enter the records:2

enter the 1 no of records:
enter the subjects:maths

enter the marks:78

enter the 2 no of records:
enter the subjects:english

enter the marks:74

displayed course record:
subjects= maths
marks= 78
subjects= english
marks= 74
------------------------------------------------------
enter the new records you want to create:2

enter the 1 no of records:
enter the subjects:programming

enter the marks:67

enter the 2 no of records:
enter the subjects:pcsoftware

enter the marks:79

displayed course record:
subjects=programming
marks=67
subjects=pcsoftware
marks=79

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C Programming Exercises With Solutions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
write c program to generate following pattern... >>
<< Write a program in c to demonstrate pointer to a p...