C Program to Store Information Using Structures with Dynamically Memory Allocation
In this example, you’ll learn to store information using structures by allocation of dynamic memory using malloc().
This program asks the user to store the value of noOfRecords and allocates the memory for the noOfRecords structure variable dynamically using malloc() function.
Example: Demonstrate the Dynamic Memory Allocation for Structure
#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);
// Allocates the memory for noOfRecords structures with pointer ptr pointing to the base address.
ptr = (struct course*) malloc (noOfRecords * sizeof(struct course));
for(i = 0; i < noOfRecords; ++i)
{
printf("Enter name of the subject and marks respectively:\n");
scanf("%s %d", &(ptr+i)->subject, &(ptr+i)->marks);
}
printf("Displaying Information:\n");
for(i = 0; i < noOfRecords ; ++i)
printf("%s\t%d\n", (ptr+i)->subject, (ptr+i)->marks);
return 0;
}
Output
Enter number of records: 2 Enter name of the subject and marks respectively: Programming 22 Enter name of the subject and marks respectively: Structure 33 Displaying Information: Programming 22 Structure 33
Here’s an example C program that uses structures and dynamically allocates memory to store information:
#include <stdio.h>
#include <stdlib.h>
struct student {
char name[50];
int age;
float gpa;
};
int main() {
int i, n;
struct student *ptr;
printf("Enter the number of students: ");
scanf("%d", &n);
// Allocate memory dynamically
ptr = (struct student*) malloc(n * sizeof(struct student));
// Get information for each student
for (i = 0; i < n; i++) {
printf("Enter name, age, and GPA for student %d:\n", i+1);
scanf("%s %d %f", (ptr+i)->name, &(ptr+i)->age, &(ptr+i)->gpa);
}
// Display information for each student
printf("\nStudent Information:\n");
for (i = 0; i < n; i++) {
printf("Name: %s, Age: %d, GPA: %.2f\n", (ptr+i)->name, (ptr+i)->age, (ptr+i)->gpa);
}
// Free dynamically allocated memory
free(ptr);
return 0;
}
Explanation: C Program to Store Information Using Structures with Dynamically Memory Allocation
- Define a structure
student
that contains the student’s name, age, and GPA. - Declare variables
i
andn
for loop counters and the number of students. - Declare a pointer
ptr
of typestruct student
that will point to the dynamically allocated memory. - Prompt the user to enter the number of students they want to store information for, and scan the input into
n
. - Allocate memory dynamically using
malloc()
based on the number of students entered by the user. - Use a loop to get the information for each student from the user, and store it in the dynamically allocated memory.
- Use another loop to display the information for each student that was stored in the dynamically allocated memory.
- Free the dynamically allocated memory using
free()
. - End the program.