Structures (struct)

⚙️ C Language 🟢 Lesson 14 of 20 📅 2026 Edition
A structure lets you group several related variables of different types together under one name. Where an array holds many values of the same type, a structure holds several values of potentially different types that describe one real-world entity.
1Defining and Using a Structure
C Language ▶ Run Code
struct Student {
    char name[50];
    int age;
    float gpa;
};

int main() {
    struct Student s1 = {"Riya", 20, 3.8};

    printf("%s is %d years old, GPA %.1f\n", s1.name, s1.age, s1.gpa);
    return 0;
}

The dot operator . accesses a specific field inside a structure variable. This groups related data logically — much cleaner than having three separate, unrelated variables floating around your program.

2Using typedef for Cleaner Code

Writing struct Student every time you declare a new variable gets repetitive. typedef lets you create a shorter alias:

C Language ▶ Run Code
typedef struct {
    char name[50];
    int age;
} Student;

int main() {
    Student s1 = {"Aman", 22};   // no 'struct' keyword needed anymore
    return 0;
}
3Arrays of Structures
C Language ▶ Run Code
typedef struct {
    char name[30];
    int score;
} Player;

int main() {
    Player team[3] = {
        {"Vikram", 85},
        {"Sana", 92},
        {"Dev", 78}
    };

    for (int i = 0; i < 3; i++) {
        printf("%s: %d\n", team[i].name, team[i].score);
    }
    return 0;
}

This pattern — an array of structures — is how you'd model something like a leaderboard, a student roster, or an inventory of products, each with the same fields but different values.

4Structures and Pointers

When working with a pointer to a structure, use the arrow operator -> instead of the dot, which automatically dereferences and accesses the field in one step:

C Language ▶ Run Code
Student s1 = {"Neha", 21, 3.9};
Student *ptr = &s1;

printf("%s\n", ptr->name);   // shorthand for (*ptr).name
⚠️ Common Mistake: Confusing . and -> Between Structs and Struct Pointers

Use the dot . operator on a regular structure variable, and the arrow -> operator on a pointer to a structure. Mixing them up — writing ptr.name instead of ptr->name — causes a compiler error, and is one of the most frequent small mistakes when first combining structures with pointers.

💻 Try It Yourself

Define a Book structure with title, author, and year fields, create two Book variables, and print both of their details.

C Language ▶ Run Code
#include <stdio.h>

typedef struct {
    char title[50];
    char author[30];
    int year;
} Book;

int main() {
    Book b1 = {"1984", "George Orwell", 1949};
    Book b2 = {"Dune", "Frank Herbert", 1965};

    printf("%s by %s (%d)\n", b1.title, b1.author, b1.year);
    printf("%s by %s (%d)\n", b2.title, b2.author, b2.year);
    return 0;
}
Run This in Our Compiler →