Store Data in Structures Dynamically in C

Exercise:

Write a C Program to store data in structures dynamically.

Click Here to View the Solution!
#include <stdio.h>       
#include <stdlib.h>
       
struct course {
    int marks;
    char subject[30];
};

int main() {
    struct course *ptr;
    int i, noOfRecords;
    printf("Enter number of records: ");
    scanf("%d", &noOfRecords);
    ptr = (struct course *)malloc(noOfRecords * sizeof(struct course));
    for (i = 0; i < noOfRecords; ++i) {
        printf("Enter the name of the subject and marks respectively:\n");
        scanf("%s %d", (ptr + i)->subject, &(ptr + i)->marks);
    }
    printf("Result Sheet:\n");
    for (i = 0; i < noOfRecords; ++i) {
        printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->marks); 
    }     
    return 0;
}
Click Here to View the Output!
Enter number of records: 3
Enter the name of the subject and marks respectively:
Maths 95
Enter the name of the subject and marks respectively:
Science 90
Enter the name of the subject and marks respectively:
Biology 93
Result Sheet :
Maths    95
Science    90
Biology    93
Click Here to View the Explanation!
  • This program is used to store the data dynamically for the demonstration of the dynamic memory allocation for Structures.
  • A Structure course is created with the members marks (integer) and a string array subject of the size 30.
  • In main(), the program requests the user to enter the number of records and stores it in the variable noOfRecords using the scanf() function. And a struct course type pointer variable ptr is declared.
  • The memory allocation for the noOfRecords in the structures is created dynamically using the malloc() function and struct course pointer and is stored in ptr.
  • A for loop is initialized which iterates from i = 0 until i < noOfRecords and in each iteration requests the user to enter name of the subject and the marks which are then stored in the struct variable members subject and marks using ptr which points at the location in the memory where the data is to be stored.
  • Finally, all the records of the students are printed.
%d bloggers like this: