C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Array of Structures Using Pointers

C Program: Array of Structures Using Pointers

C

#include <stdio.h>

 

// Define structure

struct Student {

    int roll;

    char name[50];

    float marks;

};

 

int main() {

    struct Student s[100];      // Array of structures

    struct Student *ptr;        // Pointer to structure

    int n, i;

 

    printf("Enter number of students: ");

    scanf("%d", &n);

 

    ptr = s; // Point to the first element of the array

 

    // Input details using pointer

    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 details using pointer

    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);

    }

 

    return 0;

}

Output

 
OUTPUT :
Enter number of students: 2

Enter details for student 1:
Roll Number: 101
Name: Aman
Marks: 85.6

Enter details for student 2:
Roll Number: 102
Name: Priya
Marks: 91.2

--- Student Details ---

Student 1
Roll Number: 101
Name: Aman
Marks: 85.60

Student 2
Roll Number: 102
Name: Priya
Marks: 91.20

Explanation

  • struct Student stores details of each student.
  • s is an array of structures, and ptr is a pointer to the first element of this array.
  • (ptr + i) moves the pointer to the ith student structure.
  • The arrow operator (->) is used to access each member.
  • Input and output are both performed via the pointer.