C Programming - Beginner to Brilliance / Structures and Unions

Pointers to Structures

Using pointers with structures allows you to:

  • πŸ“Œ Efficiently pass structures to functions

  • πŸ’Ύ Access and modify structure data using memory addresses

  • πŸš€ Save memory by avoiding large data copies


🧩 First, Let’s Recall a Structure Example:

struct Student {
    int id;
    char name[50];
    float marks;
};

Now let’s go step by step into using pointers to this structure.


🧷 Declaring a Pointer to Structure

You declare a pointer to a structure just like other pointers:

struct Student s1;
struct Student *ptr;

ptr = &s1;  // assign address of s1 to ptr

Now, ptr holds the address of the structure s1.


πŸ› οΈ Accessing Structure Members Using Pointer

πŸ”Ή Using (*ptr).member

(*ptr).id = 101;

πŸ”Ή This says: Go to where ptr points, then access .id

πŸ”Ή Using ptr->member (Preferred shortcut)

ptr->id = 101

βœ… This is the most common and cleanest syntax.

ptr-> means: "Go to what the pointer points to, then access the member"



πŸ”„ Passing Structure Pointer to Functions

Passing structure by pointer is efficient and allows modification of original structure.

πŸ”€ Function Definition:

void display(struct Student *s) {
    printf("ID: %d\\n", s->id);
    printf("Name: %s\\n", s->name);
    printf("Marks: %.2f\\n", s->marks);
}

πŸ”€ Calling from main():

struct Student s1 = {1, "Aman", 95.5};
display(&s1);  // pass address

🧠 Because we passed the pointer, any changes inside the function will affect the original s1.


πŸ§ͺ Modifying Structure Members via Pointer

You can even change values through pointer inside a function:

void updateMarks(struct Student *s) {
    s->marks += 5;  // add grace marks
}

🧡 Array of Structures with Pointers

You can also work with an array of structures using pointers.

struct Student students[3];
struct Student *ptr = students;  // points to first student

To access student i:

(ptr + i)->id = i + 1;

βœ… You can loop using pointers instead of array indexing!


🧠 Why Use Pointers with Structures?

βœ… Benefit

πŸ” Explanation

Efficiency

Avoids copying large structures to functions

Direct Access

Allows editing the original data

Dynamic Allocation

Required when allocating structs via malloc

Easy to Build Linked Lists

Each node stores a pointer to the next struct


πŸ“¦ Structures + Pointers + Dynamic Memory

struct Student *ptr;

ptr = (struct Student*) malloc(sizeof(struct Student));

ptr->id = 101;
strcpy(ptr->name, "Sita");
ptr->marks = 88.8;

βœ… Common in dynamic applications like:

  • Linked Lists

  • File-based Record Systems

  • Operating Systems & Drivers


❗ Common Mistakes to Avoid

⚠️ Mistake

🚫 Example

βœ… Fix

Forgetting -> with pointer

ptr.id

ptr->id

Not using malloc for dynamic pointers

struct A *p; p->x = 10;

Allocate first using malloc

Dereferencing NULL pointer

struct A *p = NULL; p->x = 10;

Always check if p != NULL