C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Access structure elements with pointer

C Program: Access structure elements with pointer

C

#include <stdio.h>

 

// Define structure

struct Student {

    int roll;

    char name[50];

    float marks;

};

 

int main() {

    struct Student s1, *ptr;

 

    // Assign pointer to structure variable

    ptr = &s1;

 

    // Input student details using pointer

    printf("Enter Roll Number: ");

    scanf("%d", &ptr->roll);

    printf("Enter Name: ");

    scanf("%s", ptr->name);

    printf("Enter Marks: ");

    scanf("%f", &ptr->marks);

 

    // Display student details using pointer

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

    printf("Roll Number: %d\n", ptr->roll);

    printf("Name: %s\n", ptr->name);

    printf("Marks: %.2f\n", ptr->marks);

 

    return 0;

}

Output

 
OUTPUT :
Enter Roll Number: 101
Enter Name: Ramesh
Enter Marks: 89.5

--- Student Details ---
Roll Number: 101
Name: Ramesh
Marks: 89.50

Explanation

  • struct Student defines three members — roll, name, and marks.
  • ptr is a pointer to a struct Student variable s1.
  • The arrow operator (->) is used to access structure members via pointer (instead of .).
    • Example:
      • Using variable: s1.roll
      • Using pointer: ptr->roll
  • Data is entered and displayed through pointer dereferencing.