Structures vs Unions in C: Memory Layout and Differences

Structures vs Unions in C: Memory Layout and Differences

Structures and unions are important user-defined data types in C programming. They allow programmers to combine multiple variables of different data types into a single logical representation. Although their syntax appears similar, their memory allocation, storage behavior, and practical applications are significantly different.

Understanding structures and unions is essential for engineering students learning Embedded C, microcontroller programming, and firmware development. These concepts are widely used in Embedded Systems and Internet of Things (IoT) applications involving sensor data, communication packets, hardware registers, and memory optimization. Students exploring the Top Embedded Training Institute in Bangalore can strengthen these programming fundamentals through practical training at Embedded Tech Development Academy (ETDA).

What Is a Structure in C?

A structure is a user-defined data type that groups multiple variables of different data types under a single name. Each member of a structure receives its own storage space, allowing all members to hold independent values simultaneously.

Structures are commonly used to represent related information such as sensor measurements, device configurations, student records, and communication parameters.

Structure Syntax in C

struct Sensor
{
    int temperature;
    float voltage;
    char status;
};

This declaration defines a structure named Sensor containing three members. Memory is allocated when a variable of this structure type is created.

Structure Example

#include <stdio.h>

struct Sensor
{
    int temperature;
    float voltage;
};

int main()
{
    struct Sensor s1;

    s1.temperature = 30;
    s1.voltage = 3.3f;

    printf("%d %.1f",
           s1.temperature, s1.voltage);

    return 0;
}

The output is 30 3.3. Both structure members retain their values independently because each member has its own storage.

What Is a Union in C?

A union is a user-defined data type that allows multiple members to share the same memory location. All union members begin at the same address, but only one member’s stored value should generally be treated as active at a time.

Unions are useful when different types of data need to occupy the same memory region at different times. This approach can reduce storage requirements in memory-constrained embedded applications.

Union Syntax in C

union Data
{
    int integer;
    float decimal;
    char character;
};

The union contains three members, but their storage overlaps. The union allocates enough memory to accommodate its largest member, subject to alignment requirements.

Union Example

#include <stdio.h>

union Data
{
    int integer;
    float decimal;
};

int main()
{
    union Data d;

    d.integer = 100;
    printf("%d\n", d.integer);

    d.decimal = 5.5f;
    printf("%.1f", d.decimal);

    return 0;
}

Initially, the union stores an integer. After assigning a floating-point value, the decimal member becomes the active value. Reading the previously stored integer as though it remained unchanged is not valid portable practice.

Structures vs Unions: Memory Layout

The most important difference between structures and unions is how memory is allocated for their members.

Structure Memory Allocation

In a structure, every member has separate storage. The compiler may insert padding bytes between members or at the end to satisfy alignment requirements.

Consider:

struct Example
{
    char a;
    int b;
    char c;
};

The structure contains three members, but its total size may exceed the sum of their individual sizes because of padding.

Union Memory Allocation

In a union, all members share the same memory region. The union’s size is sufficient for its largest member and may include additional padding to satisfy alignment requirements.

union Example
{
    char a;
    int b;
    float c;
};

The union size is generally at least the size of its largest member, but the exact result depends on the compiler, platform, and alignment rules.

Difference Between Structures and Unions in C

FeatureStructureUnion
Memory allocationSeparate storage for membersShared storage
Member valuesAll can coexistTypically one active value
SizeIncludes members and paddingBased on largest member and alignment
AddressMembers have distinct storage locationsMembers begin at same address
Data modificationUpdating one member preserves othersWriting another member changes shared storage
Memory efficiencyMay require more memoryCan reduce memory usage
ApplicationRecords and configurationsVariant data and memory optimization

Both structures and unions support member access using the dot operator. When accessing members through pointers, the arrow operator is used.

Understanding sizeof with Structures and Unions

The sizeof operator determines the memory size of a data type or variable in bytes. It is useful for understanding memory allocation and validating assumptions during Embedded C development.

sizeof Structure Example

struct Test
{
    char a;
    int b;
};

printf("%zu", sizeof(struct Test));

The result may be larger than the combined sizes of char and int because the compiler can insert padding for alignment.

sizeof Union Example

union Test
{
    char a;
    int b;
};

printf("%zu", sizeof(union Test));

The union size is generally sufficient for the largest member, including any padding needed for alignment.

Applications of Structures and Unions in Embedded Systems

Structures and unions are extensively used in embedded firmware, Internet of Things (IoT) devices, automotive electronics, and microcontroller programming.

Structures in Embedded Applications

Structures organize related information into meaningful data objects.

Examples include:

  • Sensor measurement records.

  • UART communication configurations.

  • CAN message metadata.

  • Device initialization parameters.

  • Motor-control settings.

Structures improve code readability and simplify passing related information between functions.

Unions in Embedded Applications

Unions are useful when memory must represent different data formats depending on application conditions.

For example, a communication protocol may contain different payload types. A union can represent alternative payload formats while a separate identifier determines which member is valid.

However, unions should be used carefully. Type interpretation, alignment, endianness, and compiler behavior must be considered when handling binary data.

Structures and Unions in IoT Development

Internet of Things (IoT) applications frequently process sensor information, communication packets, and device configuration data.

Structures help organize temperature, humidity, pressure, and battery measurements into a single logical object. Unions can support alternative data representations when an application requires memory-efficient storage.

Understanding both concepts enables students to develop better firmware architecture and write more maintainable Embedded C programs.

Learn Embedded C at Embedded Tech Development Academy

Engineering students interested in Embedded Systems and Internet of Things (IoT) careers should understand structures, unions, pointers, arrays, and memory allocation.

Embedded Tech Development Academy (ETDA) focuses on practical technical learning involving Embedded C, microcontrollers, communication protocols, and industry-oriented projects. Students can connect programming concepts with real applications involving sensor interfaces, firmware development, and hardware interaction.

Choosing the Top Embedded Training Institute in Bangalore requires evaluating practical exposure, technical curriculum, project opportunities, and career preparation. Embedded Tech Development Academy (ETDA) emphasizes hands-on learning and assured placement support to help aspiring engineers prepare for embedded development opportunities.

Frequently Asked Questions

What is the main difference between structures and unions in C?

Structures allocate separate storage for each member, while unions allow all members to share the same memory location.

A structure generally requires space for all members and padding. A union generally requires space for its largest member and alignment requirements.

A union can contain multiple members, but their storage overlaps. Generally, only the most recently written member should be accessed as the active value.

Unions can reduce memory usage when alternative data representations are needed. They are useful in firmware, protocol handling, and memory-constrained applications.

Padding refers to extra bytes inserted by the compiler to satisfy memory alignment requirements. It can increase the total size of a structure.

Embedded Tech Development Academy (ETDA) offers practical Embedded C and Embedded Systems training with technical project exposure and assured placement support for aspiring engineers.

Conclusion

Structures and unions are essential C programming concepts that help developers organize information and manage memory effectively. Structures provide independent storage for every member, while unions allow multiple members to share the same memory region.

Understanding memory layout, padding, alignment, and sizeof is especially important for Embedded Systems and Internet of Things (IoT) programming. Engineering students should practice these concepts using Embedded C and microcontroller projects.

Embedded Tech Development Academy (ETDA) provides practical technical training and assured placement support for aspiring embedded professionals. Students seeking the Top Embedded Training Institute in Bangalore can strengthen their programming fundamentals and prepare for industry-oriented development careers.

Author: ETDA Trainers
Experience: 10+ Years of Industry Experience in Embedded Systems, IoT, and Embedded C Programming