Just like with primitive data types (int, float), you can declare and use pointers to structures. Pointers to structures are fundamental for dynamic memory allocation of structures and for implementing complex data structures like linked lists.
1. Declaring a Pointer to a Structure
To declare a pointer to a structure, you use the standard pointer declaration syntax (*), prefixed by the struct keyword and the structure name.
Syntax: struct structureName *pointerName;
Example
struct Point {
int x;
int y;
};
// 1. Declare a regular structure variable
struct Point p1 = {10, 20};
// 2. Declare a pointer to the structure
struct Point *p_ptr;
2. Initializing the Pointer
The structure pointer must be initialized with the memory address of an existing structure variable or a dynamically allocated block of structure memory.
A. Static Initialization
Assign the address of the existing variable using the address-of operator (&).
// p_ptr now holds the address of the structure p1
p_ptr = &p1;
B. Dynamic Initialization
Allocate memory from the heap sufficient for one structure using malloc() or calloc().
// Allocate space for one 'struct Point' and cast the void pointer
struct Point *p_dynamic = (struct Point *)malloc(sizeof(struct Point));
3. Accessing Members: The Arrow Operator (->)
When you have a pointer to a structure, you cannot use the dot operator (.) directly. You must first dereference the pointer and then use the dot operator.
Method 1: Using Dereference and Dot
// Parentheses are REQUIRED due to operator precedence
// This expression means: "Dereference p_ptr, then access the x member."
(*p_ptr).x = 5;
Because accessing members via a pointer is extremely common, C provides a shorthand operator: the arrow operator (->).
Method 2: Using the Arrow Operator (Shorthand)
The arrow operator performs the dereferencing and member access simultaneously, making the code cleaner and easier to read.
Syntax: pointerName->member;
// These two lines are functionally identical:
p_ptr->y = 100;
(*p_ptr).y = 100;
printf("X coordinate via pointer: %d\n", p_ptr->x);
4. Passing Structures to Functions
When you pass a large structure to a function by value, the entire structure is copied onto the stack, which is inefficient. It is standard practice to pass structures by reference (using a pointer) to improve performance and allow the function to modify the original data.
Example: Passing by Reference
// Function accepts a pointer to a Book structure
void update_price(struct Book *b_ptr, float new_price) {
// Use the arrow operator to modify the original structure's member
b_ptr->price = new_price;
}
int main() {
struct Book book1 = {"Title", "Author", 20.00};
// Pass the address of book1
update_price(&book1, 35.99);
printf("Updated Price: %.2f\n", book1.price);
return 0;
}
