In C, a struct allows you to group different data types together under a single name. While passing a struct to a function by value is easy, it is notoriously inefficient. When you pass a struct by value, the entire chunk of memory is copied. If the struct is large, this wastes CPU time and memory.
The solution is to use pointers to structs. By passing the memory address of the struct instead of the whole struct, you drastically improve performance and allow functions to modify the original struct's data.
Creating a pointer to a struct is similar to creating a pointer to any fundamental data type like int or float.
#include <stdio.h>struct Point { int x; int y; };
int main() { // Create a regular struct variable struct Point p1 = {10, 20}; // Create a pointer to the struct struct Point *ptr = &p1; printf("Pointer created successfully!\n"); return 0; }
->)When you have a regular struct variable, you access its members using the dot operator (.).
However, when you are working with a pointer to a struct, you cannot use the dot operator directly on the pointer. Instead, C provides the arrow operator (->) to dereference the pointer and access the member in one clean step.
#include <stdio.h>struct Player { char name[50]; int health; };
int main() { struct Player p1 = {"Arthur", 100}; struct Player *ptr = &p1; // Accessing via pointer (arrow operator) printf("Name via pointer: %s\n", ptr->name); // Modifying data via pointer ptr->health -= 15; // Arthur takes 15 damage printf("Current Health: %d\n", p1.health); // Prints 85 return 0; }
> Note: ptr->health is exactly equivalent to writing (*ptr).health. The arrow operator was introduced simply because typing (*ptr).health repeatedly is cumbersome!
To modify a struct inside a function, or to simply pass a large struct efficiently without copying it, you should pass a pointer to the struct as the function argument.
#include <stdio.h>struct Rectangle { int width; int height; int area; };
// Function takes a pointer to the struct void calculateArea(struct Rectangle *rect) { // We use the arrow operator because rect is a pointer rect->area = rect->width * rect->height; }
int main() { struct Rectangle box = {5, 10, 0}; // Pass the memory address of the struct calculateArea(&box); // The original struct has been modified! printf("Area after: %d\n", box.area); return 0; }
Which operator must be used to access a struct's members when you are working with a pointer to that struct?