Structures vs Unions in C



Structures and unions in C programming are user-defined data types that are used for storing different types of data together in a single block defined with curly braces {}. The main difference between a structure and a union is in the way they store and manage memory for their members.

In this chapter, we will see how structures and unions work in C and how their memory is allocated. Let's move forward and learn about −

Structure in C

A structure in C is a user-defined data type that groups variables of different data types under one name. A structure is defined using the struct keyword, and when defining a structure no memory is allocated. Memory is allocated only when we declare variables of that structure type, and each member gets its own separate memory location.

Members of a structure are accessed using the dot (.) operator when working with structure variables, and the arrow (->) operator when working with pointers to a structure. Structures are useful for storing records like a student's details, an address, etc.

Syntax of Structure

Following is the syntax for declaring a structure in C −

struct structure_name {
    data_type member1;
    data_type member2;
    ...
    data_type memberN;
};

Here, struct is the keyword used to define a structure. structure_name is the name of the structure and member1, member2, etc., are the data members of different data types.

Example of a Structure

Below is a C program where we define a structure Student with three members: roll_no, name, and marks. We create a variable s1, assign values to its members, and then print them. Each member has its own memory, so changing one does not affect the others.

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

// Define a structure to store student details
struct Student {
    int roll_no;
    char name[50];
    float marks;
};

int main() {
    struct Student s1;        // Create a structure variable

    s1.roll_no = 101;         // Assign roll number
    strcpy(s1.name, "Amit");  // Assign name
    s1.marks = 89.5;          // Assign marks

    // Print student details
    printf("Roll No: %d\n", s1.roll_no);
    printf("Name: %s\n", s1.name);
    printf("Marks: %.2f\n", s1.marks);
    return 0;
}

Following is the output of the program. It displays the student details stored in the structure −

Roll No: 101
Name: Amit
Marks: 89.50

Example of a Structure Holding Pointers to Another Structure

In this example, we have two structures: Student and Address. The Student structure has a pointer addr to an Address structure. First, we create an Address variable and assign its address to a Student variable s1. Then, we display the student's details along with the city and state from Address structure.

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

// Structure for Address
struct Address {
    char city[50];
    char state[50];
};

// Structure for Student
struct Student {
    char name[50];
    int roll_no;
    struct Address *addr; // Pointer to Address structure
};

int main() {
    // Create an Address dynamically
    struct Address *a1 = malloc(sizeof(struct Address));
    strcpy(a1->city, "Mumbai");
    strcpy(a1->state, "Maharashtra");

    // Create a Student and assign Address pointer
    struct Student s1;
    strcpy(s1.name, "jony");
    s1.roll_no = 101;
    s1.addr = a1; // Assign address pointer

    // Display Student information along with Address
    printf("Name: %s\n", s1.name);
    printf("Roll No: %d\n", s1.roll_no);
    printf("City: %s\n", s1.addr->city);
    printf("State: %s\n", s1.addr->state);

    // Free dynamically allocated memory
    free(a1);
    return 0;
}

The output displays the student's details along with the city and state from the associated Address structure using the pointer.

Name: Jony
Roll No: 101
City: Mumbai
State: Maharashtra

Union in C

A union in C is a user-defined data type that stores different types of data in the same memory location. It is defined using the union keyword, and all members share the same memory, so updating one member changes the content of the others.

The size of a union equals the size of its largest member. At any given time, only one member contains valid data because all members share the same memory, so initializing another member will overwrite the current value.

We access union members using the dot (.) operator for union variables or the arrow (->) operator for union pointers. Unions are useful when memory is limited and only one value is needed at a time.

Syntax of a Union

Following is the syntax for declaring a union in C −

union union_name {
   data_type member1;
   data_type member2;
   ...
   data_type memberN;
};

Here, union is the keyword to define the union. union_name is the name of union and and member1, member2, etc., are the data members of different data types.

Example of a Union

Below is an example where we created a union Data with three members: an integer, a float, and a character, and then a variable d. Since all members share the same memory, assigning a new value replaces the previous one. So assigning d.f overwrites d.i, and assigning d.c overwrites d.f, as shown below.

#include <stdio.h>

union Data {
    int i;
    float f;
    char c;
};

int main() {
    union Data d;  // create a union variable

    d.i = 10;      // assign an integer
    printf("i = %d\n", d.i);

    d.f = 22.5;    // assign a float (replaces integer)
    printf("f = %.2f\n", d.f);

    d.c = 'X';     // assign a character (replaces float)
    printf("c = %c\n", d.c);
    return 0;
}

Following is the output of the program, which shows that each new assignment overwrites the earlier one.

i = 10
f = 22.50
c = X    

Memory Allocation Difference

This is the most important difference between a structure and a union. The way memory is allocated to their members is different, and this affects the total size they take.

  • In a structure, every member has its own memory, so the total size is the sum of all members plus any padding added by the compiler for alignment.
  • In a union, all members share the same memory, so the total size is equal to the largest member only.

Example of Memory Allocation

In the example below, we define both a structure and a union with the same members, then calculate their sizes and display them. This clearly shows how memory is allocated differently for each.

#include <stdio.h>

struct ExampleStruct {
    int a;     // 4 bytes
    float b;   // 4 bytes
    char c;    // 1 byte (plus padding)
};

union ExampleUnion {
    int a;     // 4 bytes
    float b;   // 4 bytes
    char c;    // 1 byte
};

int main() {
    printf("Size of Structure: %lu\n", sizeof(struct ExampleStruct));
    printf("Size of Union: %lu\n", sizeof(union ExampleUnion));
    return 0;
}

The program prints the memory used by the structure and the union. The output may vary slightly on different systems or compilers.

Size of Structure: 12
Size of Union: 4

Key Differences between Structures and Unions

The following table compares and contrasts the most important features structures and unions in C −

Feature Structure Union
Memory allocation Each member gets its own memory, so all members exist independently All members share the same memory, so only one member holds a valid value at a time
Size Total size = sum of all members (plus padding if needed) Total size = size of the largest member only
Member access You can access all members simultaneously Only one member can be reliably used at a time
Initialization You can initialize all members at the time of declaration Only the first member can be initialized during declaration
Data storage Can hold multiple values at the same time Can hold only one value at a time
Best used when All properties are needed together Memory saving is important and only one value is needed at a time

Conclusion

In this chapter, we learned about structures and unions in C. Structures help us store and access multiple values together, while unions are useful when memory is limited and only one value is needed at a time.

Advertisements