Back to C Programming
2026-07-146 min read

C - Structures vs Unions

Learn C - Structures vs Unions step by step with clear examples and exercises.

Why This Matters

Welcome to this detailed guide on C structures and unions, aimed at helping you understand these essential data types in C programming. This lesson is designed to provide practical depth, focusing on real-world scenarios, common mistakes, and interview-ready one-liners that set it apart from other tutorials. Let's dive into the world of C data types!

Why This Matters

Understanding structures and unions in C programming is crucial for several reasons:

  1. Organizing complex data: Structures allow you to group related variables together, making your code more readable and manageable.
  2. Saving memory: Unions provide a way to save memory by allowing multiple variables to occupy the same memory location.
  3. Preparing for interviews: Knowledge of structures and unions is essential for cracking coding interviews and solving real-world programming problems.
  4. Debugging and troubleshooting: Understanding these data types can help you debug complex programs and understand how data is being manipulated in memory.

Prerequisites

Before diving into structures and unions, it's essential to have a good understanding of the following topics:

  1. C basics: Variables, constants, operators, control statements, functions, and arrays.
  2. Pointers: Understanding pointers is crucial for working with structures and unions effectively.
  3. Memory management: Concepts such as stack and heap memory are important for understanding how structures and unions work in C programming.

Core Concept

Structures

A structure (abbreviated as struct) is a user-defined data type that allows you to group related variables together. Each variable within a structure is called a member, and each member has a unique name and data type. To declare a structure, you use the struct keyword followed by the structure tag (a name given to the structure) and enclose its members in curly braces {}.

struct Student {
int roll_number;
char name[50];
float marks;
};

In this example, we have defined a structure called Student with three members: roll_number, name, and marks. To create an instance of the Student structure, you allocate memory for it using the struct Student data type.

struct Student s1; // Declaring a variable of type struct Student

To access a member of a structure, you use the dot (.) operator followed by the structure variable and the member name.

s1.roll_number = 1;
strcpy(s1.name, "John Doe");
s1.marks = 85.5;

Unions

A union is a user-defined data type that allows multiple variables to occupy the same memory location. This can be useful when you want to store different types of data in the same place, as it saves memory by avoiding unnecessary duplication. To declare a union, you use the union keyword followed by the union tag (a name given to the union) and enclose its members in curly braces {}.

union Data {
int i;
float f;
char str[20];
};

In this example, we have defined a union called Data with three members: i, f, and str. To access a member of a union, you use the dot (.) operator followed by the union variable and the offset number of the desired member. The offset numbers for each member are determined based on their size in bytes.

union Data data;
data.i = 42; // Storing an integer in the union
printf("%s\n", data.str); // Output: empty string (since we haven't set the char array)
data.f = 3.14; // Overwriting the integer with a float value
printf("The float value is: %.2f\n", data.f); // Output: The float value is: 3.14

Worked Example

Let's create a program that uses both structures and unions to store information about a student and their favorite book.

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

// Define the structure for Student
struct Student {
int roll_number;
char name[50];
float marks;
};

// Define the union for Book
union Book {
char title[30];
int pages;
};

int main() {
// Declare a variable of type struct Student and union Book
struct Student s1;
union Book b1;

// Initialize the student data
s1.roll_number = 1;
strcpy(s1.name, "John Doe");
s1.marks = 85.5;

// Initialize the book data
strcpy(b1.title, "The C Programming Language");

// Print the student and book information
printf("Student Information:\n");
printf("Roll Number: %d\n", s1.roll_number);
printf("Name: %s\n", s1.name);
printf("Marks: %.2f\n", s1.marks);
printf("\nBook Information:\n");
printf("Title: %s\n", b1.title);
printf("Number of Pages: %d\n", sizeof(b1.pages)); // Print the size of the int member (since we haven't set the pages value)

return 0;
}

When you run this program, it will output the following:

Student Information:
Roll Number: 1
Name: John Doe
Marks: 85.50

Book Information:
Title: The C Programming Language
Number of Pages: 4

Common Mistakes

  1. Forgetting to initialize structure members: It's essential to initialize all the members of a structure, as uninitialized variables contain garbage values that can lead to unexpected behavior in your program.
  2. Accessing out-of-bounds array elements: When working with structures containing arrays, ensure you don't access elements outside the defined bounds, which can result in segmentation faults or other runtime errors.
  3. Confusing structure and union members: Remember that each member of a structure occupies its own memory location, while each member of a union shares the same memory location.
  4. Using incorrect offset numbers for union members: Ensure you use the correct offset number when accessing union members, as this can lead to unexpected behavior or data corruption.
  5. Misunderstanding the size of unions: Unions can be tricky to work with because their size depends on the largest member they contain at any given time. Be mindful of this when using unions in your code.

Practice Questions

  1. Create a structure called Address that includes members for street, city, state, and zip code. Write a program that initializes an instance of this structure and prints the address information.
  2. Modify the worked example to include a union member for the book author's name. Add functionality to print the author's name along with the title and number of pages.
  3. Create a structure called Employee that includes members for employee ID, name, department, and salary. Write a program that initializes an array of 5 Employee structures, sorts them in ascending order based on their salaries, and prints the sorted list.

FAQ

  1. Why can't I access union members directly using their names like structure members?

Union members don't have unique memory locations, so you cannot access them directly by name. Instead, you must use offset numbers to access the desired member.

  1. Is it possible to store different types of data in a single variable using structures?

Yes, it is possible to store different types of data in a single variable using structures, but each member occupies its own memory location, unlike unions that share the same memory location for all members.

  1. Can I have an array of structures or unions in C?

Yes, you can declare and use arrays of both structures and unions in C programming.

  1. What are some common uses for unions in real-world programming scenarios?

Unions can be useful when you need to store different types of data in the same memory location, such as when working with network packets or device registers that require flexible data representation.