C Program to Store Information using Structures with Dynamic Memory Allocation
C program to store information using structures with dynamic memory allocation.
In this article, you will learn how to write a C program to store the student's information using the C structure and Dynamic Memory Allocation. We will use the C pointers
& malloc()
function to implement this program.
Example
Enter the record count: 2
Enter the student's information(Name, Email, and Class):
david david@email.com 10
Enter the student's information(Name, Email, and Class):
roy roy@email.com 11
Student's Information:
-----------------------------------------------------
david david@email.com 10
-----------------------------------------------------
roy roy@email.com 11
-----------------------------------------------------
You should know about the following topics in C programming to understand this program:
- C Structure
- C Pointers
- Dynamic Memory Allocation in C
Source
// C Program to Store Information using Structures with Dynamic Memory Allocation
#include <stdio.h>
#include <stdlib.h>
// Make the structure of the student records
struct students {
char name[25];
char email[25];
int class;
};
// It's the main function of the program
int main() {
struct students *pointer;
int records_count;
// Step-1 INPUT the no. of records
printf("Enter the record count: ");
scanf("%d", &records_count);
// Step-2 Allocate the memories to the counted records by using the `malloc` function
pointer = (struct students *)malloc(records_count * sizeof(struct students));
// Step-3 Iterate over the counted records to take the inputs from the user
for (int i = 0; i < records_count; i++) {
printf("\nEnter the student's information(Name, Email, and Class):\n");
scanf("%s %s %d", (pointer + i)->name, (pointer + i)->email, &(pointer + i)->class);
}
// Step-4 Final output of the program to display the student records
printf("\nStudent's Information:\n");
printf("-----------------------------------------------------\n");
for (int i = 0; i < records_count; i++) {
printf("%s\t%s\t%d\n", (pointer + i)->name, (pointer + i)->email, (pointer + i)->class);
printf("-----------------------------------------------------\n");
}
return 0;
}
Output
Enter the record count: 4
Enter the student's information(Name, Email, and Class):
david david@yahoo.com 10
Enter the student's information(Name, Email, and Class):
robert robert@yahoo.com 10
Enter the student's information(Name, Email, and Class):
johny johny@email.com 12
Enter the student's information(Name, Email, and Class):
sandy sandy@email.com 11
Student's Information:
-----------------------------------------------------
david david@yahoo.com 10
-----------------------------------------------------
robert robert@yahoo.com 10
-----------------------------------------------------
johny johny@email.com 12
-----------------------------------------------------
sandy sandy@email.com 11
-----------------------------------------------------