Q:

C program to read and print the N student details using structure and Dynamic Memory Allocation.

0

C program to read and print the N student details using structure and Dynamic Memory Allocation.

In this program we will create a structure with N number of student details and print the inputted details. Memory to store and print structure will be allocated at run time by using malloc() and released by free().

All Answers

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

/*C program to read and print the N student 
details using structure and Dynamic Memory Allocation.*/
 
#include <stdio.h>
#include <stdlib.h>
 
/*structure declaration*/
struct student
{
    char name[30];
    int roll;
    float perc;
};
 
int main()
{
    struct student *pstd;
    int n,i;
     
    printf("Enter total number of elements: ");
    scanf("%d",&n);
     
    /*Allocate memory dynamically for n objetcs*/
    pstd=(struct student*)malloc(n*sizeof(struct student));
     
    if(pstd==NULL)
    {
        printf("Insufficient Memory, Exiting... \n");
        return 0;
    }
     
    /*read and print details*/
    for(i=0; i<n; i++)
    {
        printf("\nEnter detail of student [%3d]:\n",i+1);
        printf("Enter name: ");
        scanf(" "); /*clear input buffer*/
        gets((pstd+i)->name);
        printf("Enter roll number: ");
        scanf("%d",&(pstd+i)->roll);
        printf("Enter percentage: ");
        scanf("%f",&(pstd+i)->perc);
    }
     
    printf("\nEntered details are:\n");
    for(i=0; i<n; i++)
    {
        printf("%30s \t %5d \t %.2f\n",(pstd+i)->name,(pstd+i)->roll,(pstd+i)->perc);
    }
      
    return 0;
}
    Enter total number of elements: 3 

    Enter detail of student [1]:
    Enter name: Mike
    Enter roll number: 1
    Enter percentage: 87.50 

    Enter detail of student [2]:
    Enter name: Jussy 
    Enter roll number: 2
    Enter percentage: 88

    Enter detail of student [3]:
    Enter name: Macalla 
    Enter roll number: 3
    Enter percentage: 98.70 

    Entered details are:
                              Mike 1 87.50
                             Jussy 2 88.00
                           Macalla 3 98.70

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

total answers (1)

C program to read and print the student details us... >>