Structures and Unions

Structures and unions! These are fundamental data types in C that help in managing and organizing data efficiently.

Structures (Structs)

Structures allow you to group different types of data into a single unit. This is useful for representing complex data.

Declaration and Definition

To define a structure, use the struct keyword followed by the structure name and the body containing the members.

#include <stdio.h>

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

int main() {
    // Declare and initialize a structure variable
    struct Person person1 = {"Alice", 30, 5.5};
    
    printf("Name: %s\n", person1.name);   // Outputs: Alice
    printf("Age: %d\n", person1.age);     // Outputs: 30
    printf("Height: %.1f\n", person1.height);  // Outputs: 5.5
    
    return 0;
}

Explanation:

  • Structure Definition: struct Person defines a structure with name, age, and height.

  • Access Members: Use the dot operator . to access members of a structure.

Dynamic Allocation with Structures

You can also dynamically allocate memory for structures using pointers.

Explanation:

  • malloc allocates memory for the structure.

  • Use -> to access members of a structure via a pointer.

  • free releases the allocated memory.


Unions

Unions are similar to structures but differ in how they manage memory. A union allows different data types to share the same memory location.

Declaration and Definition

To define a union, use the union keyword followed by the union name and its members.

Explanation:

  • Memory Sharing: All members of a union share the same memory location. Changing one member affects the others.

  • Size: The size of a union is determined by the size of its largest member.


Comparison: Structures vs. Unions

  • Structures: Each member has its own memory location. Size is the sum of sizes of all members.

  • Unions: All members share the same memory location. Size is the size of the largest member.


Using Structures and Unions

  1. Structures: Ideal for cases where you need to group data but keep them distinct.

  2. Unions: Useful when you need to store different types of data but only one at a time.

Example: Combining Structures and Unions

Explanation:

  • Combining: A struct can contain a union to allow different types of data in the same structure.


Summary

  • Structures group different data types into a single unit.

  • Unions allow different data types to share the same memory location, useful for memory-efficient storage when only one type is needed at a time.

  • Dynamic Allocation for structures allows flexible memory management.

  • Combining structures and unions can be powerful for complex data representations.


Last updated

Was this helpful?