C Structure Pointers – Access Structure Members Using Pointers
In C, pointers can also be used with structures. This is super useful when you’re dealing with dynamic memory or passing structures to functions efficiently.
🔹 Structure Pointer Syntax
You can create a pointer to a structure and use the arrow operator ->
to access its members.
📝 Example: Access Structure Using Pointer
This example shows how to define a structure, assign values, and access members using a pointer.
#include <stdio.h> #include <string.h> struct Student { int roll; char name[30]; float marks; }; int main() { struct Student stu1; struct Student *ptr; // Assign values using normal way stu1.roll = 101; strcpy(stu1.name, "Alice"); stu1.marks = 89.5; // Assign address to pointer ptr = &stu1; // Access members using pointer printf("Roll No: %d\n", ptr->roll); printf("Name: %s\n", ptr->name); printf("Marks: %.2f\n", ptr->marks); return 0; }
📌 Quick Note
- Use
ptr->member
instead of(*ptr).member
. Both work the same, but the arrow syntax is easier and cleaner. - This method is especially useful when structures are passed to functions via pointers or dynamically allocated.
🎯 Fun Practice!
Try modifying the example to use an array of structures and pointers. Experiment with accessing and modifying different elements!