C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Structure with Dynamic Memory Allocation using Pointer

C Program: Structure with Dynamic Memory Allocation using Pointer

C

#include <stdio.h>

#include <stdlib.h>

 

// Define structure

struct Student {

    int roll;

    char name[50];

    float marks;

};

 

int main() {

    int n, i;

    struct Student *ptr;

 

    printf("Enter number of students: ");

    scanf("%d", &n);

 

    // Dynamically allocate memory for n students

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

 

    if (ptr == NULL) {

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

        return 1;

    }

 

    // Input student details

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

        printf("\nEnter details for student %d:\n", i + 1);

        printf("Roll Number: ");

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

        printf("Name: ");

        scanf("%s", ptr[i].name);

        printf("Marks: ");

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

    }

 

    // Display student details

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

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

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

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

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

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

    }

 

    // Free allocated memory

    free(ptr);

 

    return 0;

}

Output

 
OUTPUT :
Enter number of students: 2

Enter details for student 1:
Roll Number: 101
Name: Ravi
Marks: 88.5

Enter details for student 2:
Roll Number: 102
Name: Meena
Marks: 92.0

--- Student Details ---

Student 1
Roll Number: 101
Name: Ravi
Marks: 88.50

Student 2
Roll Number: 102
Name: Meena
Marks: 92.00

Explanation

  • The program dynamically allocates memory for multiple Student structures using malloc().
  • It allows user input for each student’s details.
  • Data is accessed using array indexing (ptr[i]).
  • Finally, the memory is freed using free() to prevent memory leaks.