Structures (struct) & Arrow

🔵 C Programming Lesson 11 Intermediate

Structures (struct) group variables of different data types under a single, unified type name. They are the foundation of custom data models in C.

1 Declaring Structs and Memory Layouts

A struct allocates space for all of its member fields in memory sequentially. Members are accessed using the dot operator (`.`).

2 Pointers to Structures & The Arrow (->) Operator

If you have a pointer to a struct, accessing members via dereferencing requires parentheses due to operator precedence rules: `(*ptr).age`. To make the syntax cleaner, C provides the **Arrow Operator (`->`)**, which is equivalent: `ptr->age`. Let's test this behavior:

C — Structs & Arrow Operators ▶ Run Code
#include <stdio.h>

// Declare the Structure model
struct Student {
    char name[30];
    int rollNumber;
    float gpa;
};

int main() {
    // Initialize structure variable
    struct Student s1 = {"Alice", 101, 3.85f};
    
    // Print details using dot operator
    printf("Student: %s, GPA: %.2f\n", s1.name, s1.gpa);

    // Pointer to structure
    struct Student *sPtr = &s1;

    // Modify members using the Arrow operator (->)
    sPtr->gpa = 3.95f;
    printf("Updated GPA via pointer ->: %.2f\n", s1.gpa);

    return 0;
}
3 Code Challenge
Challenge: Write a struct called `Point` containing two integer fields: `x` and `y`. Declare a Point variable, assign coordinates, create a pointer to it, and print the coordinates using the arrow operator.