C Tutorial

Understanding Structures and Unions in C


Introduction

Structures and unions are composite data types in C that allow you to group variables of different data types under a single name. These data structures are essential for organizing and manipulating data effectively in your programs. In this guide, we'll provide an in-depth explanation of structures and unions, along with sample code to illustrate their usage.

Structures

A structure is a user-defined data type in C that groups variables of different data types under a single name. Each variable within a structure is referred to as a `member` or `field.` Structures provide a convenient way to represent and manage complex data.

Sample Code for Structures

#include <stdio.h> // Define a structure struct Student { char name[50]; int age; float gpa; }; int main() { // Declare a structure variable struct Student student1; // Initialize structure members strcpy(student1.name, `Alice`); student1.age = 20; student1.gpa = 3.7; // Access and display structure members printf(`Student Info:\n`); printf(`Name: %s\n`, student1.name); printf(`Age: %d\n`, student1.age); printf(`GPA: %.2f\n`, student1.gpa); return 0; }

Unions

A union is similar to a structure but has a crucial difference: all members of a union share the same memory location. This means that a union can only store the value of one of its members at a time. Unions are often used to save memory when multiple data types are associated with a single entity.

Sample Code for Unions

#include <stdio.h> // Define a union union NumericValue { int integer; float floating; }; int main() { // Declare a union variable union NumericValue value; // Initialize and access union members value.integer = 42; printf(`Integer Value: %d\n`, value.integer); value.floating = 3.14159; printf(`Floating Point Value: %.2f\n`, value.floating); return 0; }

Conclusion

Structures and unions in C are powerful data structures that facilitate the organization and manipulation of complex data. This guide provided a detailed explanation of structures and unions, along with sample code for both. As you continue your C programming journey, you'll find these data structures to be invaluable for representing and working with various types of data.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.