A pointer to structure in C is a pointer variable that stores the memory address of a structure variable. Using this pointer, we can access the members of the structure indirectly using the -> (arrow) operator.
This is particularly useful when:
- Passing structures to functions efficiently.
- Dynamically allocating memory for structures.
- Handling arrays or linked lists of structures.
Why Use Pointer to Structure?
- Saves memory and improves performance when passing large structures to functions.
- Enables dynamic memory allocation of structures using malloc().
- Facilitates complex data structures like linked lists, trees, and graphs.
Syntax:
struct StructureName {
data_type member1;
data_type member2;
};
struct StructureName *ptr;To point ptr to a structure variable:
ptr = &structure_variable;Accessing Members Using Pointer:
- Use the arrow operator -> to access structure members via a pointer:
ptr->member1Example: Pointer to Structure:
#include <stdio.h>
#include <string.h>
// Define a structure
struct Student {
int roll;
char name[50];
float marks;
};
int main() {
struct Student s1 = {101, "Ravi", 88.5};
// Declare a pointer to the structure
struct Student *ptr;
// Assign address of s1 to pointer
ptr = &s1;
// 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;
}Output:
Roll No: 101
Name: Ravi
Marks: 88.50