Exploring Structures and Unions in ‘C’ for Efficient Member Access

C Programming @ Freshers.in

C, a versatile and powerful programming language, offers various data structures to organize and manage data efficiently. Among these, structures and unions are fundamental constructs that allow you to group related data members into a single entity. In this article, we will dive deep into the world of structures and unions in C, focusing on accessing structure members effectively.

Understanding Structures and Unions

Structures

A structure in C is a composite data type that groups together variables of different data types under a single name. Each variable within a structure is called a member, and you can access these members using the dot (.) operator. Here’s a basic example:

#include <stdio.h>
// Define a structure
struct Student {
    char name[50];
    int age;
    float marks;
};
int main() {
    // Create a structure variable
    struct Student student1;
    // Access structure members
    strcpy(student1.name, "John Doe");
    student1.age = 20;
    student1.marks = 85.5;
    // Display student information
    printf("Name: %s\n", student1.name);
    printf("Age: %d\n", student1.age);
    printf("Marks: %.2f\n", student1.marks);
    return 0;
}

Output:

Name: John Doe
Age: 20
Marks: 85.50

Unions

Unions, on the other hand, are similar to structures but with a key difference – they share memory space among their members. This means that only one member of a union can be active at a time. Here’s an example:

#include <stdio.h>
// Define a union
union Money {
    int dollars;
    float euros;
    double pounds;
};
int main() {
    // Create a union variable
    union Money cash;
    // Access union members
    cash.dollars = 100;
    printf("Dollars: %d\n", cash.dollars);
    cash.euros = 75.50;
    printf("Euros: %.2f\n", cash.euros);
    cash.pounds = 150.75;
    printf("Pounds: %.2lf\n", cash.pounds);
    return 0;
}

Output:

Dollars: 100
Euros: 75.50
Pounds: 150.75

Practical Applications

Structures and unions are extensively used in C to represent complex data types. They are invaluable in scenarios such as:

  • Storing and manipulating data records (e.g., student records, employee information).
  • Parsing data from files or network protocols.
  • Managing memory efficiently by sharing space (unions).
Author: user