5. C Structures, Unions & Enums

Comprehensive Guide: User-defined composite data types, struct member access, arrow operator -> & memory unions

Module 1: C Structures (struct) & Arrow Operator

Grouping variables of different data types under a single user-defined record type.

🇬🇧 English Definition

A structure is a user-defined composite data type in C that allows grouping variables of different data types under a single name.

🇮🇳 Hinglish Definition

Structure se hum naya custom data type bana sakte hai jisme alag-alag types (int, float, char) ka data ek saath grouping me reh sakta hai.

Core Concepts & Rules

  • Member access using dot operator: student1.id.
  • Structure pointer access using arrow operator: ptr->id.
  • Memory size of struct equals sum of member sizes (plus alignment padding).

🔍 Line-by-Line Code Breakdown

  1. Line 1-4: Define struct Student with fields id and marks.
  2. Line 7: Instantiate struct Student s1 = {101, 98.5}.
  3. Line 8: Declare structure pointer ptr pointing to &s1.
  4. Line 9-10: Print fields using arrow operator ptr->id and ptr->marks.
💻 Practical C Code Example - C Structures (struct) & Arrow Operator
struct Student {
    int id;
    float marks;
};

int main() {
    struct Student s1 = {101, 98.5f};
    struct Student *ptr = &s1;

    printf("Student ID: %d\n", ptr->id);
    printf("Marks: %.1f\n", ptr->marks);
    return 0;
}
📤 Compiled Program Output:
Student ID: 101 Marks: 98.5

Module 2: Unions (union) vs Structures Memory Allocation

Sharing memory space between different fields to minimize RAM footprint.

🇬🇧 English Definition

A union is a special data type that allows storing different data types in the SAME memory location, allocating size equal to its largest member.

🇮🇳 Hinglish Definition

Union me saare members EK HI memory location share karte hai. Memory size sabse bade member ke barabar hoti hai.

Core Concepts & Rules

  • Only ONE member of a union can contain a valid value at any given time.
  • Saves RAM memory in embedded hardware systems.

🔍 Line-by-Line Code Breakdown

  1. Line 1-4: Define union Data with int i and float f sharing same RAM memory.
  2. Line 7: Assign d.i = 50 and print.
💻 Practical C Code Example - Unions (union) vs Structures Memory Allocation
union Data {
    int i;
    float f;
};

int main() {
    union Data d;
    d.i = 50;
    printf("Union Integer Value: %d\n", d.i);
    return 0;
}
📤 Compiled Program Output:
Union Integer Value: 50