Back to course

Pointers to Structures (The '->' Operator)

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 43: Pointers to Structures (The -> Operator)

Structures are often passed to functions using pointers to save memory and allow for modification (Call by Reference).

Declaring a Pointer to a Structure

c struct Person { char name[30]; int age; };

struct Person p1 = {"John", 45}; struct Person *ptr_p1; // Declare a pointer to a Person structure

ptr_p1 = &p1; // Assign the address of p1 to the pointer

Accessing Members via Pointer

There are two equivalent ways to access a structure member using a pointer:

1. Dereference and Dot Operator

First dereference the pointer, then use the dot operator.

c (*ptr_p1).age = 46; printf("Age: %d\n", (*ptr_p1).age);

2. The Arrow Operator (->)

C provides a shorthand, the arrow operator (->), which is usually clearer and preferred.

c ptr_p1->age = 47; // Equivalent to (*ptr_p1).age = 47 printf("Name: %s\n", ptr_p1->name);

Dynamic Allocation of Structures

Structures can be allocated on the heap using malloc() or calloc(), which always returns a pointer to the structure.

c struct Person *new_person = (struct Person *) malloc(sizeof(struct Person));

if (new_person != NULL) { new_person->age = 25; // Don't forget to free later! free(new_person); }