Pointers to structures

Lesson 6.4: Pointers to Structures


In previous lessons, you've learned how to work with structures directly. Now, we'll dive into pointers to structures, a fundamental concept that enables you to manipulate structures more efficiently and build complex data structures like linked lists.


Why Pointers to Structures?


Dynamic Memory Allocation: Pointers allow you to create structures in dynamic memory (heap) using functions like malloc(), which is essential for data structures that grow and shrink during program execution.

Passing to Functions: When you pass a structure by value to a function, the entire structure is copied, which can be inefficient for large structures. Passing a pointer to a structure avoids this overhead.

Data Structures: Pointers to structures are the building blocks for creating linked lists, trees, graphs, and other complex data structures.

Declaring a Pointer to a Structure


The syntax for declaring a pointer to a structure is similar to declaring a pointer to any other data type:

C

struct structName *ptr;


Example:

C

struct Point {

    int x;

    int y;

};


struct Point *p; // Declare a pointer 'p' that can point to a Point structure


Accessing Members through Pointers


Arrow Operator (->): You can access the members of a structure through a pointer using the arrow operator. This operator combines dereferencing the pointer (*) and accessing the member (.) in a single step.

C

struct Point p1 = {5, 10};

p = &p1; // Assign the address of p1 to p

printf("x: %d, y: %d\n", p->x, p->y);  // Access members using the arrow operator


Alternative (with * and .): You can also use the indirection (*) and dot (.) operators separately:

C

printf("x: %d, y: %d\n", (*p).x, (*p).y); 

Use code with caution.

Dynamically Allocating Structures


You can use malloc() to allocate memory for a structure dynamically:


C

p = (struct Point*)malloc(sizeof(struct Point)); 

if (p != NULL) { // Check if allocation was successful

    p->x = 5; 

    p->y = 10;

} else {

    // Handle memory allocation error

}

Key Points:


Pointers: Store memory addresses of structures.

Arrow Operator (->): Convenient way to access structure members through pointers.

Dynamic Allocation: malloc() allocates memory for structures on the heap.

Don't Forget to Free: Always use free() to deallocate dynamically allocated memory when you're done with it.

Example: Passing a Pointer to a Function


C

void movePoint(struct Point *p, int dx, int dy) {

    p->x += dx;

    p->y += dy;

}


// ... 

movePoint(&p1, 3, -2); // Move the point (5, 10) to (8, 8)

Hands-On Exercise:


Create a structure Rectangle with members for width and height.

Write a function calculateArea that takes a pointer to a Rectangle and returns the area.

In main, dynamically allocate a Rectangle, set its dimensions, and use the calculateArea function to find and print its area.

Course Syllabus