C Structures

Grouping related data together

🏗️ What are C Structures?

Structures in C allow you to group related variables of different data types under a single name, making it easier to organize and manage complex data in your programs.


// Simple structure example
struct Student {
    char name[50];
    int age;
    float grade;
};
                                    

Structure Concepts

📦

Definition

Create a structure template

struct Point {
    int x, y;
};
🎯

Declaration

Create structure variables

struct Point p1, p2;

Initialization

Set initial values

struct Point p = {10, 20};
🔍

Access

Use dot operator to access members

p.x = 5;
printf("%d", p.y);

🔹 Basic Structure Example

Structures in C allow you to group related variables of different types under a single name, creating custom data types that model real-world entities. You define a structure using the struct keyword followed by a name and member declarations in braces, like struct Person {char name[50]; int age; float height;}; Then create variables with struct Person p1; and access members using the dot operator: p1.age = 25; Structures are fundamental to organizing complex data, making programs more readable and maintainable. They're used to represent everything from simple coordinates to complex database records, forming the backbone of data organization in C programming and enabling you to model real-world concepts directly in code.

#include <stdio.h>
#include <string.h>

// Define a structure
struct Student {
    char name[50];
    int age;
    float grade;
};

int main() {
    // Declare and initialize
    struct Student s1;
    
    // Assign values
    strcpy(s1.name, "John");
    s1.age = 20;
    s1.grade = 85.5;
    
    // Display values
    printf("Name: %s\n", s1.name);
    printf("Age: %d\n", s1.age);
    printf("Grade: %.1f\n", s1.grade);
    
    return 0;
}

Output:

Name: John
Age: 20
Grade: 85.5

🔹 Structure Initialization Methods

C provides multiple ways to initialize structures, ranging from designated initializers to compound literals, giving you flexibility in different situations. You can initialize during declaration with struct Point p = {10, 20}; or use designated initializers struct Point p = {.x = 10, .y = 20}; which explicitly name members and allow any order. C99 introduced compound literals like p = (struct Point){30, 40}; for assignment after declaration. You can also initialize member by member after declaration using the dot operator. Partial initialization sets specified members to given values and automatically zeros remaining members. Understanding these methods helps you write clearer, more maintainable code by choosing the most appropriate initialization style for each situation.

#include <stdio.h>

struct Rectangle {
    int width;
    int height;
};

int main() {
    // Method 1: Initialize during declaration
    struct Rectangle r1 = {10, 5};
    
    // Method 2: Initialize with member names
    struct Rectangle r2 = {.width = 15, .height = 8};
    
    // Method 3: Assign after declaration
    struct Rectangle r3;
    r3.width = 20;
    r3.height = 12;
    
    printf("Rectangle 1: %d x %d\n", r1.width, r1.height);
    printf("Rectangle 2: %d x %d\n", r2.width, r2.height);
    printf("Rectangle 3: %d x %d\n", r3.width, r3.height);
    
    return 0;
}

Output:

Rectangle 1: 10 x 5
Rectangle 2: 15 x 8
Rectangle 3: 20 x 12

🔹 Nested Structures

Nested structures allow you to embed one structure inside another, creating hierarchical data organizations that model complex real-world relationships. For example, a struct Employee might contain a struct Date for the hire date and a struct Address for location information. You access nested members using multiple dot operators like employee.hireDate.year or employee.address.city. This approach provides natural organization for complex data, making code more intuitive and self-documenting. Nested structures are commonly used in applications dealing with structured data like personnel records, geographical information, or configuration settings. They help maintain logical groupings of related data while keeping the code organized and the relationships between data elements clear and maintainable.

#include <stdio.h>

struct Date {
    int day;
    int month;
    int year;
};

struct Employee {
    char name[50];
    int id;
    struct Date joinDate;
};

int main() {
    struct Employee emp = {
        "Alice Smith",
        101,
        {15, 6, 2023}
    };
    
    printf("Employee: %s\n", emp.name);
    printf("ID: %d\n", emp.id);
    printf("Join Date: %d/%d/%d\n", 
           emp.joinDate.day, 
           emp.joinDate.month, 
           emp.joinDate.year);
    
    return 0;
}

Output:

Employee: Alice Smith
ID: 101
Join Date: 15/6/2023

🔹 Array of Structures

Arrays of structures enable you to create collections of similar structured data, perfect for managing multiple records in applications like databases or inventories. You declare them like struct Student class[50]; which creates 50 Student structures, each accessible by index: class[0].name, class[1].age, etc. This pattern is essential for applications that process multiple similar items, such as student grade systems, employee databases, or product inventories. You can iterate through the array using loops to process all records, making operations like searching, sorting, and reporting straightforward. Arrays of structures provide an organized way to handle bulk data while maintaining the benefits of structured data types, combining the power of both language features effectively.

#include <stdio.h>

struct Book {
    char title[30];
    int pages;
    float price;
};

int main() {
    struct Book library[3] = {
        {"C Programming", 450, 29.99},
        {"Data Structures", 380, 34.50},
        {"Algorithms", 520, 39.99}
    };
    
    printf("Library Books:\n");
    for(int i = 0; i < 3; i++) {
        printf("%d. %s - %d pages - $%.2f\n", 
               i+1, library[i].title, 
               library[i].pages, library[i].price);
    }
    
    return 0;
}

Output:

Library Books:
1. C Programming - 450 pages - $29.99
2. Data Structures - 380 pages - $34.50
3. Algorithms - 520 pages - $39.99

🧠 Test Your Knowledge

Which operator is used to access structure members?