C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Dynamic Memory Allocation in C

Dynamic Structure Allocation (Student Information)

C Program: Dynamic Structure Allocation (Student Information)

C

#include <stdio.h>

#include <stdlib.h>

 

struct Student {

    int roll;

    char name[50];

    float marks;

};

 

int main() {

    struct Student *students;

    int n, i;

 

    // Step 1: Input number of students

    printf("Enter number of students: ");

    scanf("%d", &n);

 

    // Step 2: Allocate memory dynamically

    students = (struct Student*) malloc(n * sizeof(struct Student));

    if (students == NULL) {

        printf("Memory allocation failed!\n");

        return 1;

    }

 

    // Step 3: Input student details

    printf("\nEnter details of students:\n");

    for (i = 0; i < n; i++) {

        printf("\nStudent %d\n", i + 1);

        printf("Enter Roll No: ");

        scanf("%d", &students[i].roll);

        printf("Enter Name: ");

        scanf(" %[^\n]", students[i].name);  // Read full name with spaces

        printf("Enter Marks: ");

        scanf("%f", &students[i].marks);

    }

 

    // Step 4: Display student details

    printf("\n----- Student Information -----\n");

    for (i = 0; i < n; i++) {

        printf("\nStudent %d:\n", i + 1);

        printf("Roll No: %d\n", students[i].roll);

        printf("Name   : %s\n", students[i].name);

        printf("Marks  : %.2f\n", students[i].marks);

    }

 

    // Step 5: Free dynamically allocated memory

    free(students);

 

    return 0;

}

Output

 
OUTPUT :
Enter number of students: 2

Enter details of students:

Student 1
Enter Roll No: 101
Enter Name: Alice Johnson
Enter Marks: 89.5

Student 2
Enter Roll No: 102
Enter Name: Bob Smith
Enter Marks: 92.0

----- Student Information -----

Student 1:
Roll No: 101
Name   : Alice Johnson
Marks  : 89.50

Student 2:
Roll No: 102
Name   : Bob Smith
Marks  : 92.00


Explanation

Step

Description

struct Student

Defines a structure for roll number, name, and marks.

malloc()

Allocates memory for n students at runtime.

scanf(" %[^\n]", str)

Reads full name including spaces.

free()

Releases dynamically allocated memory to prevent memory leaks.